/* Reads in the GSU Gender and Commpetitiveness 2022 Data */

* log file
log using "Raven Gender and Competitiveness 2024.log", replace name(raven)

* configure Stata
capture: version 18
set processors 4
set more off
set scheme s1color
set seed 987654321
timer clear 1
timer on 1

* graphics font
graph set window fontface "Candara"

* tell us what version ran
about

* task need to be run first, then restart with "n"
global getRisk "y"

* use the recovered beliefs rather than reports
global useRECOVERED "y"

* tasks
global doData "y"
global doRaven "y"

* local for starting subject in Raven pictures
local StartSubject = 1

* create directories needed
capture: mkdir figures

* get the recovered beliefs ready for merge
if "$useRECOVERED" == "y" {

	foreach m in eut rdu {

		cd "Recover Beliefs"
			use gc_`m'_summary, clear
		cd ..
		generate str30 Task = "5. Piece Rate Rank?" if qid == "tournament_5"
		replace Task = "6. Tournament Rank?" if qid == "tournament_6"
		compress Task
		keep uid b_1 b_2 b_3 b_4 qid Task
		tab Task qid, missing
		sort uid Task
		des
		reshape long b_, i(uid qid) j(bbin)
		rename b_ belief
		sort uid Task bbin
		des
		save tmp_beliefs_`m', replace

	}

}

* get risk preferences
qui {
if "$getRisk" == "y" {

local risk_model "eut2022"
cd "Recover Beliefs"
	use bhm_`risk_model'_posterior
cd ..
summ _loglikelihood if id==1
local mcmc = r(N)
rename _loglikelihood ll
drop if id==.
summ uid
local uid_min = r(min)
local uid_max = r(max)
generate r_uid = .
forvalues x=`uid_min'/`uid_max' {
	count if uid == `x'
	local nobs = r(N)
	if `nobs' > 0 {
		foreach p in r {
			summ `p' if uid == `x'
			replace `p'_uid = r(mean) if uid==`x'
		}
	}
}

keep uid r_uid
summ
drop if r_uid == .
summ
bysort uid: egen int record=seq()
keep if record==1
drop record
rename r_uid r_eut
sort uid
save risk_preferences_eut, replace


local risk_model "rdu2022"
cd "Recover Beliefs"
	use bhm_`risk_model'_posterior
cd ..
summ _loglikelihood if id==1
local mcmc = r(N)
rename _loglikelihood ll
drop if id==.
summ uid
local uid_min = r(min)
local uid_max = r(max)
generate r_uid = .
generate eta_uid = .
generate phi_uid = .
forvalues x=`uid_min'/`uid_max' {
	count if uid == `x'
	local nobs = r(N)
	if `nobs' > 0 {
		foreach p in r eta phi {
			summ `p' if uid == `x'
			replace `p'_uid = r(mean) if uid==`x'
		}
	}
}

keep uid r_uid eta_uid phi_uid
summ
drop if r_uid == .
summ
bysort uid: egen int record=seq()
keep if record==1
drop record
rename r_uid r_rdu
rename eta_uid eta
rename phi_uid phi
sort uid
save risk_preferences_rdu, replace

}
else {
	use risk_preferences_eut, clear
	summ uid
	local uid_min = r(min)
	local uid_max = r(max)
	forvalues x=`uid_min'/`uid_max' {
		count if uid == `x'
		local nobs = r(N)
		if `nobs' > 0 {
			foreach p in r_eut {
				summ `p' if uid == `x'
				local `p'_`x' = r(mean)
			}
		}
	}

	use risk_preferences_rdu, clear
	summ uid
	local uid_min = r(min)
	local uid_max = r(max)
	forvalues x=`uid_min'/`uid_max' {
		count if uid == `x'
		local nobs = r(N)
		if `nobs' > 0 {
			foreach p in r_rdu eta phi {
				summ `p' if uid == `x'
				local `p'_`x' = r(mean)
			}
			noi: di "EUT risk preferences for subject `x': EUT r is `r_eut_`x'', and RDU r, eta and phi are `r_rdu_`x'', `eta_`x'' and `phi_`x''"
		}
	}
	noi: di "* Risk preferences have been read in..."
}

* end of qui
}

* program to read in the data
program define get_survey

* Raven score
rename SC0 raven_score
label variable raven_score "Score out of 12 from Set I of Raven Advanced Progressive Matrices test"
capture: destring raven_score, replace force
tab raven_score, missing

* big five inventory
forvalues x=1/44 {
	rename Q34_`x' bfi`x'
}
foreach q in 6 21 31 2 12 27 37 8 18 23 43 9 24 34 35 41 {
	generate int bfi`q'r = .
	replace bfi`q'r = 5 if bfi`q' == 1
	replace bfi`q'r = 4 if bfi`q' == 2
	replace bfi`q'r = 3 if bfi`q' == 3
	replace bfi`q'r = 2 if bfi`q' == 4
	replace bfi`q'r = 1 if bfi`q' == 5
}

egen int bfi_extra = rowmean(bfi1 bfi6r bfi11 bfi16 bfi21r bfi26 bfi31r bfi36)
egen int bfi_agree = rowmean(bfi2r bfi7 bfi12r bfi17 bfi22 bfi27r bfi32 bfi37r bfi42)
egen int bfi_cons = rowmean(bfi3 bfi8r bfi13 bfi18r bfi23r bfi28 bfi33 bfi38 bfi43r)
egen int bfi_neur = rowmean(bfi4 bfi9r bfi14 bfi19 bfi24r bfi29 bfi34r bfi39)
egen int bfi_open = rowmean(bfi5 bfi10 bfi15 bfi20 bfi25 bfi30 bfi35r bfi40 bfi41r bfi44)

label variable bfi_extra "BFI Extraversion"
label variable bfi_agree "BFI Agreeableness"
label variable bfi_cons "BFI Conscientiousness"
label variable bfi_neur "BFI Neuroticism"
label variable bfi_open "BFI Openness"

des bfi_*
summ bfi_*
pwcorr bfi_*

forvalues x=1/44 {
	drop bfi`x'
}
foreach q in 6 21 31 2 12 27 37 8 18 23 43 9 24 34 35 41 {
	drop bfi`q'r
}



/* 
To score the BFI, you’ll first need to reverse-score all negatively-keyed items:

Extraversion: 6, 21, 31
Agreeableness: 2, 12, 27, 37
Conscientiousness: 8, 18, 23, 43
Neuroticism: 9, 24, 34
Openness: 35, 41

To recode these items, you should subtract your score for all reverse-scored items from 6. For example, if you gave yourself a 5, compute 6 minus 5 and your recoded score is 1. 
That is, a score of 1 becomes 5, 2 becomes 4, 3 remains 3, 4 becomes 2, and 5 becomes 1.

Next, you will create scale scores by averaging the following items for each B5 domain (where R indicates using the reverse-scored item).

Extraversion: 1, 6R 11, 16, 21R, 26, 31R, 36
Agreeableness: 2R, 7, 12R, 17, 22, 27R, 32, 37R, 42
Conscientiousness: 3, 8R, 13, 18R, 23R, 28, 33, 38, 43R
Neuroticism: 4, 9R, 14, 19, 24R, 29, 34R, 39
Openness: 5, 10, 15, 20, 25, 30, 35R, 40, 41R, 44
*/

* define demographics
	
	*What is your age? Q14
	rename Q14 age
	destring age, replace
	replace age = age
	compress age
	des age
	tab age, missing
	la var age "Age"
	gen int age2 = age*age
	la var age2 "Age squared"

	
	generate int young=0
	generate int old=0
	replace young=1 if age<=20
	replace old=1 if age>=23
	tab young old
	label variable young "Aged 20 and under"
	label variable old "Aged 23 and older"

	*What is your gender Q15
	rename Q15 sex
	compress sex
	tab sex, missing
	generate int female=0
	replace female=1 if sex==1
	tab female, missing
	label variable female "Female"
	
	generate int male=0
	replace male=1 if sex==2
	tab male, missing
	label variable male "Male"
	
	generate int thirdgen=0
	replace thirdgen=1 if sex==3
	tab thirdgen, missing
	label variable thirdgen "Other"


	*Which of the following categories best describes you? Q16
	*updated to include Other Race category
	rename Q16 race
	tab race
	tab race, missing
	generate int black=0
	replace black=1 if race==2 | race==3
	generate int asian=0
	replace asian=1 if race==4 | race==5
	generate int white=0
	replace white=1 if race==1
	generate int hispanic=0
	replace hispanic=1 if race==6 | race==8
	generate int race_other=0
	replace race_other=1 if race==9 | race==10 | race==11
	label variable black "Black"
	label variable asian "Asian"
	label variable white "White"
	label variable hispanic "Hispanic"
	label variable hispanic "Other Race"
	tab black
	tab asian
	tab white
	tab hispanic
	tab race_other

	* major listed in many part questions
	*What is your major (select all that apply)? Q17_1 through Q17_5
	*Q4_17_TEXT is user entered, thus needs to be UPDATED BY HAND to include any additional business majors
	*updated to use string position of common terms to define a business major: Accounting, Economics, and Finance. 
	gen int business = 0
	foreach x in 1 2 3 4 {
		capture: destring Q17_`x', replace force
		replace business = 1 if Q17_`x' == 1
	}
	tab business
	label variable business "Business major"

	*What is your class standing? Q18
	*added Postbaccalaureate to include Other and Master students. Defined them with upperclass
	rename Q18 class
	tab class, nolabel
	generate int freshman=0
	replace freshman=1 if class==1
	generate int sophomore=0
	replace sophomore=1 if class==6
	generate int junior=0
	replace junior=1 if class==2
	generate int senior=0
	replace senior=1 if class==5
	generate int postbac=0
	replace postbac=1 if class==3 | class==4
	summ freshman sophomore junior senior postbac
	label variable freshman "Freshman"
	label variable sophomore "Sophomore"
	label variable junior "Junior"
	label variable senior "Senior"
	label variable postbac "Postbaccalaureate"
	gen int underclass=0
	replace underclass=1 if freshman==1 | sophomore==1
	gen int upperclass=0
	replace upperclass=1 if junior==1 | senior==1 | postbac==1
	la var underclass "Freshman or Sophomore"
	la var upperclass "Junior, Senior, or Postbac"
	tab freshman
	tab sophomore
	tab junior
	tab senior
	tab postbac
	
	*What is the highest level of education you expect to complete? Q19
	rename Q19 eduexp
	tab eduexp, nolabel
	gen int eduassoc=0
	replace eduassoc=1 if eduexp==1
	gen int edubach=0
	replace edubach=1 if eduexp==2
	gen int edudoc=0
	replace edudoc=1 if eduexp==3
	gen int eduprof=0
	replace eduprof=1 if eduexp==4
	gen int edumast=0
	replace edumast=1 if eduexp==5
	la var eduassoc "Associate's Degree"
	la var edubach "Bachelor's Degree"
	la var edudoc "Doctoral Degree"
	la var eduprof "First Professional Degree"
	la var edumast "Master's Degree"
	gen int edubachelor=0
	replace edubachelor=1 if eduassoc==1|edubach==1
	gen int eduhighbach=0
	replace eduhighbach=1 if edudoc==1|eduprof==1|edumast==1
	la var eduhighbach "Expected education higher than bachelor"
	la var edubachelor "Expected education associate or bachelor"

	*What was the highest level of education that your father (or male guardian)completed? Q20
	rename Q20 edufa
	tab edufa
	gen int edufauni=0
	replace edufauni=1 if edufa==1
	gen int edufahisch=0
	replace edufahisch=1 if edufa==3|edufa==4|edufa==6
	gen int edufaless=0
	replace edufaless=1 if edufa==5
	gen int edufadkna=0
	replace edufadkna=1 if edufa==2 | edufa==.
	la var edufauni "Father Education College or University"
	la var edufahisch "Father Education High School"
	la var edufaless "Father Education Less than High School"
	la var edufadkna "Father Education Don't Know / Not Applicable" 
	
	*What was the highest level of education that your mother (or female guardian) completed? Q21
	rename Q21 edumo
	tab edumo
	gen int edumouni=0
	replace edumouni=1 if edumo==1
	gen int edumohisch=0
	replace edumohisch=1 if edumo==3|edumo==4|edumo==6
	gen int edumoless=0
	replace edumoless=1 if edumo==5
	gen int edumodkna=0
	replace edumodkna=1 if edumo==2 | edumo==.
	la var edumouni "Mother Education College or University"
	la var edumohisch "Mother Education High School"
	la var edumoless "Mother Education Less than High School"
	la var edumodkna "Mother Education Don't Know / Not Applicable" 
	
	*What is your citizenship status in the United States? Q22
	rename Q22 citizen 
	tab citizen, missing
	gen int UScitizen=0
	replace UScitizen=1 if citizen==4 
	label var UScitizen "U.S. Citizen"
	
	*Are you a foreign student on a Student Visa? Q23
	rename Q23 studentvisa
	tab studentvisa
	gen int studvisa=0
	replace studvisa=1 if studentvisa==2
	la var studvisa "Foreign student on Student Visa"
	
	*On a 4-point scale, what is your current GPA if you are doing a Bachelor's degree, or
	*what was it when you did a Bachelor's degree? This GPA should refer to all of your
	*coursework, not just the current year. Q24
	rename Q24 Q_24
	tab Q_24
	gen int gpa=0
	replace gpa=1 if Q_24==8
	replace gpa=2 if Q_24==1
	replace gpa=3 if Q_24==2
	replace gpa=4 if Q_24==3
	replace gpa=5 if Q_24==4
	replace gpa=6 if Q_24==5
	replace gpa=7 if Q_24==6
	replace gpa=99 if Q_24==7
	la var gpa "GPA"
	label define gpal 1 "Less than 1.25" 2 "1.25 to 1.74" 3 "1.75 to 2.24" 4 "2.25 to 2.74" 5 "2.75 to 3.24" 6 "3.25 to 3.74" 7 "3.75 to 4.0" 99 "no grade" 

	label values gpa gpal
	tab gpa	
	
	generate int gpaHI=0
	replace gpaHI=1 if gpa==6 
	generate int gpaVHI=0
	replace gpaVHI=1 if gpa==7
	generate int gpaLO=0
	replace gpaLO=1 if gpa==3
	generate int gpaVLO=0
	replace gpaVLO=1 if gpa==1 | gpa==2
	label variable gpaHI "High GPA"
	label variable gpaVHI "Very high GPA"
	label variable gpaLO "Low GPA"
	label variable gpaVLO "Very low GPA"

	* revise gpaHI interpretation (per DNH and 2019 Raven code)
	replace gpaHI = gpaHI + gpaVHI

	*What relationship status describes you currently?
	tab Q25
	rename Q25 marital
	generate int single=0
	replace single=1 if marital==1
	label variable single "Never married"
	
	*How many people live in your household? Q26
	tab Q26, missing
	rename Q26 nhhd
	des nhhd
	tab nhhd, missing
 	label variable nhhd "Number of people in house"
	
	*Please select the category below that best describes the total amount of INCOME earned last year by the people in YOUR HOUSEHOLD Q27
	rename Q27 Q_27
	tab Q_27
	gen int income=0
	replace income=1 if Q_27==2
	replace income=2 if Q_27==3
	replace income=3 if Q_27==4
	replace income=4 if Q_27==5
	replace income=5 if Q_27==6
	replace income=6 if Q_27==7
	replace income=7 if Q_27==8
	replace income=8 if Q_27==1
	replace income=9 if Q_27==10
	replace income=99 if Q_27==9
	replace income=88 if Q_27==11
	la var income "Household income"
	label define incomel 1 "$15,000 or under" 2 "$15,001 to $25,000" 3 "$25,001 to $35,000" 4 "$35,001 to $50,000" 5 "$50,001 to $65,000" 6 "$65,000 to $80,000" 7 "$80,001 to $100,000" 8 "$100,001 to $150,000" 9 "Over $150,000" 88 "Prefer not to answer" 99 "Don't know"
	label values income incomel
	gen int incomeHI=0
	replace incomeHI=1 if income==6|income==7
	gen int incomeVHI=0
	replace incomeVHI=1 if income==8|income==9
	tab incomeVHI, missing
	gen int incomeME=0
	replace incomeME=1 if income==4|income==5
	gen int incomeLO=0
	replace incomeLO=1 if income==3
	gen int incomeVLO=0
	replace incomeVLO=1 if income==1|income==2
	
	*Please select the category below that best describes the total amount of INCOME
	*earned last year by YOUR PARENTS / GUARDIANS. Q28
	rename Q28 Q_28
	tab Q_28
	gen int incparent=0
	replace incparent=1 if Q_28==2
	replace incparent=2 if Q_28==3
	replace incparent=3 if Q_28==4
	replace incparent=4 if Q_28==5
	replace incparent=5 if Q_28==6
	replace incparent=6 if Q_28==7
	replace incparent=7 if Q_28==8
	replace incparent=8 if Q_28==1
	replace incparent=9 if Q_28==10
	replace incparent=99 if Q_28==9
	replace incparent=88 if Q_28==11
	la var incparent "Parents' income"
	label define incparentl 1 "$15,000 or under" 2 "$15,001 to $25,000" 3 "$25,001 to $35,000" 4 "$35,001 to $50,000" 5 "$50,001 to $65,000" 6 "$65,000 to $80,000" 7 "$80,001 to $100,000" 8 "$100,001 to $150,000" 9 "Over $150,000" 88 "Prefer not to answer" 99 "Don't know"
	label values incparent incparentl
	gen int incparentHI=0
	replace incparentHI=1 if incparent==6|incparent==7
	gen int incparentVHI=0
	replace incparentVHI=1 if incparent==8|incparent==9
	gen int incparentME=0
	replace incparentME=1 if incparent==4|incparent==5
	gen int incparentLO=0
	replace incparentLO=1 if incparent==3
	gen int incparentVLO=0
	replace incparentVLO=1 if incparent==1|incparent==2
	
	*Do you work full-time, part-time, or neither? Q29
	rename Q29 Q_29
	tab Q_29
	generate int working=0
	replace working=1 if Q_29==1 | Q_29==3
	tab working, missing
	label variable work "Working part-time or full-time"
	
	*Do you currently smoke cigarettes? Q30
	rename Q30 Q_30
	tab Q_30
	generate int smoker=0
	replace smoker=1 if Q_30==1
	label variable smoker "Current smoker"
	
	*Approximately how many cigarettes do you smoke per day? Q31
	rename Q31 Q_31
	tab Q_31
	rename Q_31 cigarettes
	replace cigarettes=0 if cigarettes==.
	
	*How do you see yourself: are you a person who is fully prepared to take risks or do
	*your try to avoid taking risks? Please select an option on the scale, where 0 means
	*"not at all will to take risks" and 10 means "very willing to take risks". Q32_1
	tab Q32_1
	generate int riskaverse=0
	replace riskaverse=1 if Q32_1==1 | Q32_1==2 | Q32_1==3
	generate int riskloving=0
	replace riskloving=1 if Q32_1==10 | Q32_1==11
	summ risk*
	tab2 Q32_1 riskaverse
	tab2 Q32_1 riskloving
	gen dohmen=0
	replace dohmen=1 if Q32_1==2
	replace dohmen=2 if Q32_1==3
	replace dohmen=3 if Q32_1==4
	replace dohmen=4 if Q32_1==5
	replace dohmen=5 if Q32_1==6
	replace dohmen=6 if Q32_1==7
	replace dohmen=7 if Q32_1==8
	replace dohmen=8 if Q32_1==9
	replace dohmen=9 if Q32_1==10
	replace dohmen=10 if Q32_1==11
	tab2 Q32_1 dohmen
	label variable dohmen "Likert response on risk aversion"

	*How would you characterize your religious beliefs?
	rename Q33 Q_33
	tab Q_33
	gen int christian=0
	* most of 'others' are some kind of Christian
	replace christian=1 if Q_33==3|Q_33==4|Q_33==5|Q_33==6|Q_33==7|Q_33==12
	gen int otherreligion=0
	replace otherreligion=1 if Q_33==2|Q_33==8|Q_33==9|Q_33==10
	gen int noreligion=0
	replace noreligion=1 if Q_33==1|Q_33==11
	gen int noanswreligion=0
	replace noanswreligion=1 if Q_33==13
	la var christian "Christian"
	la var otherreligion "Buddhist, Hindu, Muslim or Jewish"
	la var noreligion "Atheist, Nonreligious, or Agnostic"
	la var noanswreligion "No answer - Religion" 
	summ christian otherreligion noreligion noanswreligion

	* seat -- note, LAB and not XLAB
	*SPS-EEC-LAB04
	*1234567890123
	generate str2 seat_txt = substr(username, 12, 2)
	destring seat_txt, replace
	generate int seat = seat_txt
	tab seat, missing
	drop seat_txt

	* fix one re-started subject for consistency across tasks -- not crucially if it is just LAB or it is XLAB
	tab username, missing
	replace username = "SPS-EEC-LAB21" if username == "SPS-EEC-LAB35"
	tab username, missing

	* two duplicates in raven_session 13, drop the second one
	duplicates list raven_session seat if raven_session == 13
	duplicates drop raven_session seat, force

	* change the seat numbers to match the RDB data
	replace seat = 35 if seat == 21 & raven_session == 13
	replace seat = 35 if seat == 21 & raven_session == 14

* end of program
end


* read in raw data
if "$doData" == "y" {

* find the files
	cd "raw data"
		local files : dir . files "*.csv"
		di `"`files'"'
	cd ..
	noi: di "Collating raw oTree files from every 2022 Gender and Competitiveness session..."

* keep track of all files
local ff = 0

* read in full CSV and extract risk
foreach f of local files {

	di "processing file `f' for risk choices..."

	import delimited using "raw data/`f'", clear delimiters(",")
	keep if v1 == "risk"
	list in 1/11, noobs

	rename v2 session_timestamp
	*2022-03-01 132457
	*12345678901234567890
	* _startTime = Now.ToString("yyyy-MM-dd HHmmss"

	generate str4 year = substr(session_timestamp,1,4)
	generate str2 month = substr(session_timestamp,6,2)
	generate str2 day = substr(session_timestamp,9,2)
	generate str2 hour = substr(session_timestamp,12,2)
	destring year month day hour, replace
	compress year month day hour

	* extra column in later data
	if "`f'" == "raven results _sps-eec-expmonx_2022-10-26 133154.csv" | "`f'" == "raven results _sps-eec-expmonx_2022-10-27 100421.csv" { 

	rename v3 computer

	generate str2 seat = substr(computer,13,2)
	destring seat, replace
	di "here 1"
	list v1 computer seat, noobs

	rename v4 subject_id
	rename v5 period
	rename v6 stimulus_id

	local c = 6
	forvalues x=1/4 {
		local c = `c'+1
		rename v`c' Lp`x'
	}
	forvalues x=1/4 {
		local c = `c'+1
		rename v`c' La`x'
	}
	forvalues x=1/4 {
		local c = `c'+1
		rename v`c' Rp`x'
	}
	forvalues x=1/4 {
		local c = `c'+1
		rename v`c' Ra`x'
	}

	rename v23 start_time
	rename v24 duration_time_ms
	rename v25 response_value
	rename v26 response_label

	}
	else {

	rename v4 computer

	generate str2 seat = substr(computer,13,2)
	destring seat, replace
	di "here 2"
	list v1 computer seat, noobs

	rename v5 subject_id
	rename v6 period
	rename v7 stimulus_id

	local c = 7
	forvalues x=1/4 {
		local c = `c'+1
		rename v`c' Lp`x'
	}
	forvalues x=1/4 {
		local c = `c'+1
		rename v`c' La`x'
	}
	forvalues x=1/4 {
		local c = `c'+1
		rename v`c' Rp`x'
	}
	forvalues x=1/4 {
		local c = `c'+1
		rename v`c' Ra`x'
	}

	rename v24 start_time
	rename v25 duration_time_ms
	rename v26 response_value
	rename v27 response_label

	}

	drop v*
	generate str10 task = "Risk"

	* destring
	destring subject_id period Lp* La* Rp* Ra* response_value, replace
	compress
	list task year month day hour seat subject_id period stimulus_id Lp* La* Rp* Ra*  start_time duration_time_ms response_* in 1/10, noobs
	des, fullnames
	summ

	* save
	local ff = `ff'+1
	save tmp_2022_`ff', replace

* loop over files
}


* read in full CSV and extract beliefs
foreach f of local files {

	di "processing file `f' for beliefs..."

	import delimited using "raw data/`f'", clear delimiters(",")
	keep if v1 == "belief"
	list in 1/11, noobs

	rename v2 session_timestamp
	*2022-03-01 132457
	*12345678901234567890
	generate str4 year = substr(session_timestamp,1,4)
	generate str2 month = substr(session_timestamp,6,2)
	generate str2 day = substr(session_timestamp,9,2)
	generate str2 hour = substr(session_timestamp,12,2)
	destring year month day hour, replace
	compress year month day hour

	* extra column in later data
	if "`f'" == "raven results _sps-eec-expmonx_2022-10-26 133154.csv" | "`f'" == "raven results _sps-eec-expmonx_2022-10-27 100421.csv" { 

	rename v3 computer

	generate str2 seat = substr(computer,13,2)
	destring seat, replace
	di "here 3"
	list v1 computer seat, noobs

	rename v4 subject_id
	rename v5 period
	rename v6 raven_belief
	rename v7 stimulus_id

	* raven results _2022-03-25 13
	* 12345678901234567890

	rename v8 iteration

	rename v9 alpha
	rename v10 beta
	rename v11 start_time
	rename v12 duration_time_ms
	rename v13 accuracy
	rename v14 earnings
	rename v15 r1
	rename v16 r2
	rename v17 r3
	rename v18 r4
	rename v19 r5
	rename v20 r6
	rename v21 r7
	rename v22 r8
	rename v23 r9
	rename v24 r10
	drop v25 v26

	}
	else {

	rename v4 computer

	generate str2 seat = substr(computer,13,2)
	destring seat, replace
	list v1 computer seat, noobs

	rename v5 subject_id
	rename v6 period
	rename v7 raven_belief
	rename v8 stimulus_id

	* raven results _2022-03-25 13
	* 12345678901234567890

	rename v9 iteration

	rename v10 alpha
	rename v11 beta
	rename v12 start_time
	rename v13 duration_time_ms
	rename v14 accuracy
	rename v15 earnings
	rename v16 r1
	rename v17 r2
	rename v18 r3
	rename v19 r4
	rename v20 r5
	rename v21 r6
	rename v22 r7
	rename v23 r8
	rename v24 r9
	rename v25 r10
	drop v26
	capture: drop v27

	}

	summ
	generate str30 task = "Beliefs -- Correlation"
	destring raven_belief, replace
	replace task = "Beliefs -- First Raven" if raven_belief==1
	replace task = "Beliefs -- Second Raven" if raven_belief==2
	replace task = "Beliefs -- Third Raven" if raven_belief==3

	* destring
	forvalues x=1/10 {
		replace r`x' = "0" if r`x' == "NA"
	}
	destring r*, replace
	destring subject_id period alpha beta accuracy earnings, replace
	capture: destring iteration, replace
	compress
	capture: generate int iteration=.
	list task year month day hour computer seat subject_id period stimulus_id alpha beta start_time duration_time_ms accuracy earnings r* iteration in 1/10, noobs
	des, fullnames
	summ

	drop seat
	generate str2 seat = substr(computer,13,2)
	destring seat, replace

	* save
	local ff = `ff'+1
	save tmp_2022_`ff', replace

}

* read in full CSV and extract tournament 
foreach f of local files {

	di "processing file `f' for choice of Tournament or Piece Rate payment..."

	import delimited using "raw data/`f'", clear delimiters(",")
	tab v1, missing
	keep if v1 == "tournament"
	list in 1/11, noobs

	rename v2 session_timestamp
	*2022-03-01 132457
	*12345678901234567890
	generate str4 year = substr(session_timestamp,1,4)
	generate str2 month = substr(session_timestamp,6,2)
	generate str2 day = substr(session_timestamp,9,2)
	generate str2 hour = substr(session_timestamp,12,2)
	destring year month day hour, replace
	compress year month day hour

	* extra column in later data
	if "`f'" == "raven results _sps-eec-expmonx_2022-10-26 133154.csv" | "`f'" == "raven results _sps-eec-expmonx_2022-10-27 100421.csv" { 

	rename v3 computer

	generate str2 seat = substr(computer,13,2)
	destring seat, replace
	di "here 5"
	list v1 computer seat, noobs

	rename v4 subject_id
	rename v5 period
	rename v6 stimulus_id

	rename v7 payment_choice

	drop v8-v23 v24 v25 v26

	}
	else {

	rename v4 computer

	generate str2 seat = substr(computer,13,2)
	destring seat, replace

	rename v5 subject_id
	rename v6 period
	rename v7 stimulus_id

	rename v8 payment_choice

	drop v9-v23 v24 v25 v26

	}

	summ
	generate str30 task = "Tournament or Piece Rate?"

	destring subject_id period , replace
	compress
	list task year month day hour computer seat subject_id period stimulus_id payment_choice in 1/10, noobs
	des, fullnames
	summ

	drop seat
	generate str2 seat = substr(computer,13,2)
	destring seat, replace
	list v1 computer seat, noobs

	* save
	local ff = `ff'+1
	save tmp_2022_`ff', replace

}

* read in full CSV and extract beliefs
foreach f of local files {

	di "processing file `f' for Tournament beliefs..."

	import delimited using "raw data/`f'", clear delimiters(",")
	keep if v1 == "tournament_belief"
	list in 1/11, noobs

	rename v2 session_timestamp
	*2022-03-01 132457
	*12345678901234567890
	generate str4 year = substr(session_timestamp,1,4)
	generate str2 month = substr(session_timestamp,6,2)
	generate str2 day = substr(session_timestamp,9,2)
	generate str2 hour = substr(session_timestamp,12,2)
	destring year month day hour, replace
	compress year month day hour

	* extra column in later data
	if "`f'" == "raven results _sps-eec-expmonx_2022-10-26 133154.csv" | "`f'" == "raven results _sps-eec-expmonx_2022-10-27 100421.csv" { 

	rename v3 computer

	generate str2 seat = substr(computer,13,2)
	destring seat, replace
	di "here 7"
	list v1 computer seat, noobs

	rename v4 subject_id
	rename v5 period
	rename v6 stimulus_id

	* raven results _2022-03-25 13
	* 12345678901234567890

	rename v7 alpha
	rename v8 beta
	rename v9 num_tokens
	rename v10 start_time
	rename v11 duration_time_ms
	rename v12 r1
	rename v13 r2
	rename v14 r3
	rename v15 r4
	drop v16-v26

	}
	else {

	rename v4 computer

	generate str2 seat = substr(computer,13,2)
	destring seat, replace
	di "here 8"
	list v1 computer seat, noobs

	rename v5 subject_id
	rename v6 period
	rename v7 stimulus_id

	* raven results _2022-03-25 13
	* 12345678901234567890

	rename v8 alpha
	rename v9 beta
	rename v10 num_tokens
	rename v11 start_time
	rename v12 duration_time_ms
	rename v13 r1
	rename v14 r2
	rename v15 r3
	rename v16 r4
	drop v17-v26

	}

	summ
	generate str30 task = "Tournament Beliefs"

	* destring
	forvalues x=1/4 {
		replace r`x' = "0" if r`x' == "NA"
	}
	destring r*, replace
	destring subject_id period alpha beta num_tokens, replace
	compress
	list task year month day hour computer seat subject_id period stimulus_id num_tokens alpha beta start_time duration_time_ms r* in 1/10, noobs
	des, fullnames
	summ

	drop seat
	generate str2 seat = substr(computer,13,2)
	destring seat, replace

	capture: drop v1

	* save
	local ff = `ff'+1
	save tmp_2022_`ff', replace

}


* append
use tmp_2022_1, clear
forvalues x=2/`ff' {
	di "appending tmp_2002_`x'..."
	append using tmp_2022_`x'
	erase tmp_2022_`x'.dta
}
erase tmp_2022_1.dta

* check computer
tab computer, missing

* specify ravenGC sessions for risk and beliefs
generate int ravenGC_session = .
replace ravenGC_session = 1 if year==2022 & month==10 & day==26
replace ravenGC_session = 2 if year==2022 & month==10 & day==27
replace ravenGC_session = 3 if year==2022 & month==11 & day==1
replace ravenGC_session = 4 if year==2022 & month==11 & day==15
replace ravenGC_session = 5 if year==2022 & month==11 & day==16
replace ravenGC_session = 6 if year==2022 & month==11 & day==30

* moved to seat 7 for demographics
replace seat = 7 if ravenGC_session == 2 & seat == 19

* reven_session helps merge for all sessions
generate int raven_session = .
replace raven_session = 22 if ravenGC_session == 1
replace raven_session = 23 if ravenGC_session == 2
replace raven_session = 24 if ravenGC_session == 3

replace raven_session = 28 if ravenGC_session == 4
replace raven_session = 29 if ravenGC_session == 5
replace raven_session = 30 if ravenGC_session == 6

tab day month, missing
tab seat ravenGC_session, missing
tab seat ravenGC_session if period==1, missing

* update the tasks
replace task = "5. Piece Rate Rank?" if task == "Tournament Beliefs" & stimulus_id == "tournament_5"
replace task = "6. Tournament Rank?" if task == "Tournament Beliefs" & stimulus_id == "tournament_6"

replace task = "3. Select?" if task == "Tournament or Piece Rate?" & stimulus_id == "tournament_3"
replace task = "4. Submit?" if task == "Tournament or Piece Rate?" & stimulus_id == "tournament_4"

replace task = "0. Beliefs -- Correlation" if task == "Beliefs -- Correlation"
replace task = "0. Risk" if task == "Risk"
replace task = "1. Beliefs -- First Raven" if task == "Beliefs -- First Raven"
replace task = "2. Beliefs -- Second Raven" if task == "Beliefs -- Second Raven"
replace task = "3. Beliefs -- Third Raven" if task == "Beliefs -- Third Raven"

* get the tasks sorted
tab task ravenGC_session, missing

* get task by period
generate str50 Task = "0. Risk"
replace Task = "0. Scatterplot" if period>=31 & period <= 35
replace Task = "1. Raven Piece Rate" if period>=36 & period <= 47
replace Task = "2. Raven Tournament" if period>=48 & period <= 59
replace Task = "3. Select?" if period>=60 & period <= 71
replace Task = "4. Submit?" if period == 72
replace Task = "5. Piece Rate Rank?" if period == 73
replace Task = "6. Tournament Rank?" if period == 74
compress Task
tab Task ravenGC_session, missing

sort ravenGC_session year month day seat
egen int sid = group(ravenGC_session seat)
tab payment_choice if Task == "3. Select?"
tab payment_choice if Task == "4. Submit Piece Rate"
bysort sid: tab Task, missing

bysort sid: egen int record=seq()
list sid year month day seat subject_id ravenGC_session if record==1, noobs sepby(ravenGC_session)

drop v1 v3 v27

* save
sort raven_session seat Task
save tmp_raven, replace


* read in the demographics from Qualtrics
import excel using "./raw data/Raven 2022 Survey 10.xlsx", clear firstrow sheet("Data")

	compress raven_session
	tab raven_session, missing
	generate int session = raven_session

	* define the variables
	get_survey
	drop Q* Start* End* IPA* Prog* Dura* Finished Record* Recipient* Locat* UserLang* Status ResponseId External* Distrib*
	compress
	sort session seat

	* see what we have
	tab raven_session, missing
	tab seat raven_session, missing

	* merge with Raven data
	sort raven_session seat
	merge 1:m raven_session seat using tmp_raven

	* need to figure out who is missing: should be missing subjects in sessions 22, 23, 24, 28 and 29 (or just showing 1 subject)
	tab raven_session if _merge==1
	tab seat if _merge==1
	tab raven_session seat if _merge==1 & (raven_session == 22 | raven_session == 23 | raven_session == 24 | raven_session == 28 | raven_session == 29)
	tab raven_session subject_id if _merge==1 & (raven_session == 22 | raven_session == 23 | raven_session == 24 | raven_session == 28 | raven_session == 29)
	tab subject_id raven_session if (raven_session == 22 | raven_session == 23 | raven_session == 24 | raven_session == 28 | raven_session == 29)

	* add in some data for two subjects that missed Qualtrics
	replace female = 1 if raven_session == 22 & seat == 21
	replace black = 1 if raven_session == 22 & seat == 21
	replace asian = 0 if raven_session == 22 & seat == 21
	replace hispanic = 0 if raven_session == 22 & seat == 21
	replace white = 0 if raven_session == 22 & seat == 21
	replace freshman = 1 if raven_session == 22 & seat == 21
	replace sophomore = 0 if raven_session == 22 & seat == 21
	replace junior = 0 if raven_session == 22 & seat == 21
	replace senior = 0 if raven_session == 22 & seat == 21
	replace business = 0 if raven_session == 22 & seat == 21


	replace female = 1 if raven_session == 29 & seat == 5
	replace black = 0 if raven_session== 29 & seat == 5
	replace asian = 0 if raven_session== 29 & seat == 5
	replace hispanic = 1 if raven_session== 29 & seat == 5
	replace white = 0 if raven_session== 29 & seat == 5
	replace freshman = 1 if raven_session== 29 & seat == 5
	replace sophomore = 0 if raven_session== 29 & seat == 5
	replace junior = 0 if raven_session== 29 & seat == 5
	replace senior = 0 if raven_session== 29 & seat == 5
	replace business = 0 if raven_session== 29 & seat == 5

	* get a subjectid
	egen int subjectid = group(raven_session seat)

	* everyone does one iteration
	replace iteration = 1 if iteration == .

	* record per subject
	drop record
	bysort subjectid: egen int record=seq()

	* see gender choice
	tab payment_choice female if Task == "3. Select?"
	tab payment_choice female if Task == "3. Select?", col nofreq

	* document treatment
	generate int tokens = 1
	replace tokens = 80 if ravenGC_session == 1 | ravenGC_session == 2 | ravenGC_session == 3
	label variable tokens "Treatment (tokens)"

	* document who did what task
	tab task if record==1, missing
	summ subjectid
	local Nsub = r(max)
	forvalues x=1/6 {
		generate int task`x' = .
		label variable task`x' "Completed Raven task #`x'"
	}
	generate int task3s = -1
	generate int bug_free = .
	label variable task3s "Completed Raven task 3 (selection)"
	label variable task3  "Completed Raven task 3 (beliefs)"
	forvalues x=1/`Nsub' {
		qui: summ _merge if subjectid==`x'
		local m = r(mean)
		if `m'==3 {
			qui: summ subject_id if subjectid==`x'
			local sid  = r(mean)
			di " "
			di "Sequential subject ID is `x' (and subject_id read from the data file is `sid')"
			tab task if subjectid==`x' & iteration==1, missing
			tab ravenGC_session seat if subjectid==`x', missing

			summ subjectid if subjectid==`x' & task == "1. Beliefs -- First Raven" & iteration == 1
			replace task1 = r(N) if subjectid==`x' & task == "1. Beliefs -- First Raven"
			summ subjectid if subjectid==`x' & task == "2. Beliefs -- Second Raven" & iteration == 1
			replace task2 = r(N) if subjectid==`x' & task == "2. Beliefs -- Second Raven"
			summ subjectid if subjectid==`x' & task == "3. Beliefs -- Third Raven" & iteration == 1
			replace task3 = r(N) if subjectid==`x' & task == "3. Beliefs -- Third Raven"

			* the bug caused this to be missed
			summ subjectid if subjectid==`x' & task == "3. Select?"
			replace task3s = r(N) if subjectid==`x' & task == "3. Select?"
			tab task3s if subjectid==`x' & task == "3. Select?"
			local nbug = r(r)
			replace bug_free = `nbug' if subjectid==`x'
			di "This is sequential subject `x' and the tabulation for part 3 shows `nbug' rows"

			summ subjectid if subjectid==`x' & task == "4. Submit?"
			replace task4 = r(N) if subjectid==`x' & task == "4. Submit?"
			summ subjectid if subjectid==`x' & task == "5. Piece Rate Rank?"
			replace task5 = r(N) if subjectid==`x' & task == "5. Piece Rate Rank?"
			summ subjectid if subjectid==`x' & task == "6. Tournament Rank?"
			replace task6 = r(N) if subjectid==`x' & task == "6. Tournament Rank?"

		}
		else {

			replace task3s = .

		}
	}

	* see tasks
	foreach x in 1 2 3s 3 4 5 6 {
		tab task`x' tokens if _merge==3
	}

	* identify subjects hit with the bug and drop them (leave in one subject who did risk and correlation beliefs)
	tab subjectid bug_free
	drop if bug_free == 0 & ravenGC_session ~= 1 & seat ~= 21

	* flag some odd ones
	tab ravenGC_session seat if task1 == 13 & _merge==3
	tab ravenGC_session seat if task3 == 13 & _merge==3
	tab ravenGC_session seat if task3 == 14 & _merge==3

	* see the stimuli
	tab stimulus_id seat if task1 == 13 & _merge==3, missing
	tab stimulus_id seat if task3 == 13 & _merge==3, missing
	tab stimulus_id seat if task3 == 14 & _merge==3, missing

	* see the gender effect
	tab payment_choice female if Task == "3. Select?" & _merge==3
	tab payment_choice female if Task == "3. Select?" & _merge==3, col nofreq exact
	tab payment_choice female if Task == "3. Select?" & _merge==3 & tokens == 80, col nofreq exact
	tab payment_choice female if Task == "3. Select?" & _merge==3 & tokens == 1, col nofreq exact

	* now drop _merge
	drop _merge

	* save
	save ravenGC_2022, replace
	erase tmp_raven.dta

	capture: mkdir "Bayesian Hierachical Model"
	cd "Bayesian Hierachical Model"
		save ravenGC_2022, replace
	cd ..

	* see N
	tab ravenGC_session if record==1

* end of $doData
}


* process the Reven belief data 
if "$doRaven" == "y" {

* restart
use ravenGC_2022, clear

* define demographics -- most of the 2022 sample were working...
local demog    "female age black business noreligion"
local demog_i  "i.female c.age i.black i.business i.noreligion"
local demog_r  "r.female       r.black r.business r.noreligion"
local bfi      "bfi_extra bfi_agree bfi_cons bfi_neur bfi_open"

* drop session 10 -- incorrect stimuli
drop if raven_session == 10

* drop this subject, since risk and belief-correlation, but no Raven -- could be deleted by bug_free, but be safe and do it here
drop if ravenGC_session == 1 & seat == 21

* uniform ID, to link to risk preferences
generate int uid = (raven_session*100)+seat
label variable uid "Unique ID linked to raven_session and seat"

* pdf figure counter
local pdf_fig = `StartSubject'-1

* quick look at Raven
drop if task == "Beliefs -- Correlation" | task == "Risk"
tab stimulus_id, missing

* record per subject
capture: drop record
bysort raven_session seat: egen int record=seq()
label variable record "Record for each subject"

* session type
generate int eighty_tokens = 0
generate int one_token = 0

tab raven_session
keep if raven_session == 22 | raven_session == 23 | raven_session == 24 | raven_session >=28
tab raven_session

replace eighty_tokens = 0
replace eighty_tokens = 1 if raven_session == 22
replace eighty_tokens = 1 if raven_session == 23
replace eighty_tokens = 1 if raven_session == 24
replace eighty_tokens = 1 if raven_session == 30

replace one_token = 0
replace one_token = 1 if raven_session == 28
replace one_token = 1 if raven_session == 29

label variable eighty_tokens "Tournament with 80 tokens and Scrambled Raven problems"
label variable one_token "Tournament with 1 token and Scrambled Raven problems"

* gender mix
tab female
tab female one_token, col nofreq

* merge in risk preferences
qui {
	generate r_eut = .
	generate r_rdu = .
	generate eta = .
	generate phi = .
	summ uid
	local uid_min = r(min)
	local uid_max = r(max)
	forvalues x=`uid_min'/`uid_max' {
		count if uid == `x'
		local nobs = r(N)
		if `nobs' > 0 {
			qui: di "EUT risk preferences for subject `x': EUT r is `r_eut_`x'', and RDU r, eta and phi are `r_rdu_`x'', `eta_`x'' and `phi_`x''"
			replace r_eut = `r_eut_`x'' if uid==`x'
			replace r_rdu = `r_rdu_`x'' if uid==`x'
			replace eta = `eta_`x'' if uid==`x'
			replace phi = `phi_`x'' if uid==`x'
		}
	}
	noi: summ r_eut r_rdu eta phi
}
drop record
bysort uid: egen int record=seq()

* Table 2 risk parameters
bysort female: summ r_eut r_rdu eta phi if record==1 & female ~= .

* summarize BFI
summ `bfi' if record==1
bysort female: summ `bfi' if record==1

* sample sizes
local n_80 = 0
tab subjectid if eighty_tokens==1
local n_80 = r(r)
tab subjectid raven_session if eighty_tokens==1

local n_1 = 0
tab subjectid if one_token==1
local n_1 = r(r)
tab subjectid raven_session if one_token==1

tab seat ravenGC_session

di "There are `n_80' subjects in the 80-token treatment and `n_1' subjects in the 1-token treatment."

* time taken
rename duration_time_ms time_each
capture: destring time_each, force replace
bysort subject_id: egen time_raven = total(time_each)
replace time_raven = (time_raven/1000)/60
label variable time_raven "Time taken for the full Raven task, in minutes)
tab time_raven if period==36
summ time_raven if period==36, detail

* need a numeric variable for the task
tab task, generate(taskid)
local nt = r(r)
generate int task_id = .
forvalues x=1/`nt' {
	replace task_id = `x' if taskid`x' == 1
}
tab task task_id
drop taskid*

* see the payment choices
tab payment_choice if Task == "3. Select?"
tab payment_choice if Task == "4. Submit?"
tab payment_choice female if Task == "3. Select?", all col nofreq
tab payment_choice female if Task == "3. Select?" & one_token==1, all col nofreq
tab payment_choice female if Task == "3. Select?" & eighty_tokens==1, all col nofreq

generate int selectT = .
replace selectT = 0 if payment_choice == "Piece Rate" & Task == "3. Select?"
replace selectT = 1 if payment_choice == "Tournament" & Task == "3. Select?"
label variable selectT "Selected Tournament in part 3"

generate int submitT = .
replace submitT = 0 if payment_choice == "Piece Rate" & Task == "4. Submit?"
replace submitT = 1 if payment_choice == "Tournament" & Task == "4. Submit?"
label variable submitT "Submitted Tournament in part 4"

* reshape long
drop response_*
forvalues x=1/10 {
	rename r`x' report`x'
}
reshape long report, i(raven_session seat period task_id iteration) j(bbin)

* only use 8 bins for beliefs about Raven questions
drop if bbin > 8

* token allocation
generate int choiceI = 100*report
generate probs = choiceI/80
replace probs = choiceI/100 if (Task == "5. Piece Rate Rank?" | Task == "6. Tournament Rank?")
format probs %10.2f

* sequential id
drop sid
egen int sid = group(raven_session seat)
summ sid
local Nsub = r(max)

* save data for beliefs recovery
save GC_beliefs, replace
cd "Recover Beliefs"
	save GC_beliefs, replace
}

* replace with recovered beliefs for Tasks 5 and 6
if "$useRECOVERED" == "y" {

	foreach m in eut rdu {

		generate probs_`m' = probs
		replace probs_`m' = . if (Task ~= "5. Piece Rate Rank?" & Task ~= "6. Tournament Rank?")
		summ probs_`m' if (Task == "5. Piece Rate Rank?" | Task == "6. Tournament Rank?")
		merge m:1 uid Task bbin using tmp_beliefs_`m'
		drop _merge
		replace choiceI = round(belief*100,1) if (Task == "5. Piece Rate Rank?" | Task == "6. Tournament Rank?")
		summ belief choiceI
		replace probs_`m' = choiceI/100 if (Task == "5. Piece Rate Rank?" | Task == "6. Tournament Rank?")
		format probs_`m' %10.2f
		summ probs_`m' if (Task == "5. Piece Rate Rank?" | Task == "6. Tournament Rank?")
		local belief_text "Recovered Beliefs"

	}
}
else {
	replace probs = . if (Task ~= "5. Piece Rate Rank?" & Task ~= "6. Tournament Rank?")
	generate probs_reports = probs
	* in this case just use EUT or RDU for the welfare evaluation of the lotteries with reports as beliefs
	generate probs_eut = probs
	generate probs_rdu = probs
	local belief_text "Reported Beliefs"
}

* get the beliefs for the rank
* Task = "5. Piece Rate Rank?"
* Task = "6. Tournament Rank?"

capture: label define bin4 1 "Best" 2 "Second Best" 3 "Third Best" 4 "Fourth Best" 
label values bbin bin4

label define flab 0 "Male" 1 "Female"
label values female flab

* save for later use
save tmp_, replace
keep if bbin<=4
save tmp_gc4, replace
use tmp_, clear
erase tmp_.dta

* everyone
forvalues b=1/4 {
	summ choiceI probs_* if Task == "5. Piece Rate Rank?" & bbin==`b'
}
forvalues b=1/4 {
	summ choiceI probs_* if Task == "6. Tournament Rank?" & bbin==`b'
}

* males
forvalues b=1/4 {
	summ choiceI probs_* if Task == "5. Piece Rate Rank?" & bbin==`b' & female==0
}
forvalues b=1/4 {
	summ choiceI probs_* if Task == "6. Tournament Rank?" & bbin==`b' & female==0
}

* females
forvalues b=1/4 {
	summ choiceI probs_* if Task == "5. Piece Rate Rank?" & bbin==`b' & female==1
}
forvalues b=1/4 {
	summ choiceI probs_* if Task == "6. Tournament Rank?" & bbin==`b' & female==1
}
sort Task sid bbin
list Task sid bbin choiceI probs_* female if (Task == "5. Piece Rate Rank?" | Task == "6. Tournament Rank?") & bbin<=4, noobs sepby(sid)

* missing probabilities?
list sid Task earnings probs_* choiceI bbin if sid==61 & task_id>=3, noobs

* extreme propbabilities
list sid Task earnings probs_* choiceI bbin if sid==32 & task_id>=8, noobs
list sid Task earnings probs_* choiceI bbin if sid==73 & task_id>=8, noobs
list sid Task earnings probs_* choiceI bbin if sid==4 & task_id>=8, noobs
list sid Task earnings probs_* choiceI bbin if sid==10 & task_id>=8, noobs

* get the binary on whether the Tournament was selected or submitted
qui {
forvalues s=1/`Nsub' {
	summ selectT if Task == "3. Select?" & sid==`s'
	local m = r(mean)
	replace selectT = `m' if selectT == . & sid==`s'

	summ submitT if Task == "4. Submit?" & sid==`s'
	local m = r(mean)
	replace submitT = `m' if submitT == . & sid==`s'
}
}


* big loop over risk models
qui {
foreach m in eut rdu {

* get the subjective probability of top rank in the tournament where submit piece-rate
generate TwinP = .
forvalues s=1/`Nsub' {
	summ probs_`m' if Task == "5. Piece Rate Rank?" & bbin==1 & sid==`s'
	replace TwinP = r(mean) if sid==`s'
}

* get the subjective probability of top rank in the tournament
generate Twin = .
forvalues s=1/`Nsub' {
	summ probs_`m' if Task == "6. Tournament Rank?" & bbin==1 & sid==`s'
	local Twin_`s' = r(mean)
	local Twin_`s'_ = string(`Twin_`s'', "%3.2f")
	replace Twin = `Twin_`s'' if sid==`s'
}
generate TwinT = Twin

summ probs_`m' if Task == "6. Tournament Rank?" & bbin==1 & female==0 & one_token==1
local Twin_m_1 = string(r(mean), "%3.2f")
summ probs_`m' if Task == "6. Tournament Rank?" & bbin==1 & female==0 & eighty_tokens==1
local Twin_m_80 = string(r(mean), "%3.2f")
summ probs_`m' if Task == "6. Tournament Rank?" & bbin==1 & female==1 & one_token==1
local Twin_f_1 = string(r(mean), "%3.2f")
summ probs_`m' if Task == "6. Tournament Rank?" & bbin==1 & female==1 & eighty_tokens==1
local Twin_f_80 = string(r(mean), "%3.2f")

summ probs_`m' if Task == "5. Piece Rate Rank?" & bbin==1 & female==0 & one_token==1
local Twin_m_1_ns = string(r(mean), "%3.2f")
summ probs_`m' if Task == "5. Piece Rate Rank?" & bbin==1 & female==0 & eighty_tokens==1
local Twin_m_80_ns = string(r(mean), "%3.2f")
summ probs_`m' if Task == "5. Piece Rate Rank?" & bbin==1 & female==1 & one_token==1
local Twin_f_1_ns = string(r(mean), "%3.2f")
summ probs_`m' if Task == "5. Piece Rate Rank?" & bbin==1 & female==1 & eighty_tokens==1
local Twin_f_80_ns = string(r(mean), "%3.2f")

* get the subjective probability of top rank in the tournament from the piece-rate earnings
forvalues s=1/`Nsub' {
	summ probs_`m' if Task == "5. Piece Rate Rank?" & bbin==1 & sid==`s'
	local Twin_`s'_ns = r(mean)
}

* get the earnings in the piece rate and tournament
generate Ppay = .
generate Tpay = .
forvalues s=1/`Nsub' {

	* piece rate -- get paid 1 penny per point earned
	summ earnings if Task == "1. Raven Piece Rate" & bbin==1 & sid==`s'
	local Ppoints_`s' = r(mean)
	local Ppay_`s' = `Ppoints_`s''/100
	local Ppoints_`s'_ = string(`Ppoints_`s'', "%5.0f")
	local Ppay_`s'_ = string(`Ppay_`s'', "%5.2f")
	replace Ppay = `Ppay_`s'' if sid==`s'

	* tournament -- get paid 4 pennies per point earned, if top earnings
	summ earnings if Task == "2. Raven Tournament" & bbin==1 & sid==`s'
	local Tpoints_`s' = r(mean)
	local Tpay_`s' = `Tpoints_`s''/25
	local Tpoints_`s'_ = string(`Tpoints_`s'', "%5.0f")
	local Tpay_`s'_ = string(`Tpay_`s'', "%5.2f")
	replace Tpay = `Tpay_`s'' if sid==`s'

	* expected Tournament
	local Texpect_`s' = `Twin_`s''*`Tpay_`s''
	local Texpect_`s'_ = string(`Texpect_`s'', "%5.2f")

	if `s' < 5 {
		noi {
			di "Assuming `m' for beliefs, subject `s' has `Ppoints_`s'_' points and $`Ppay_`s'_' in Piece Rate, `Tpoints_`s'_' points and $`Tpay_`s'_' if winning Tournament, subjective belief of `Twin_`s'_' of winning the Tournament , so expecting $`Texpect_`s'_' from Tournament"
		}
	}
}


qui {
noi: summ earnings if Task == "1. Raven Piece Rate" & bbin==1 & female==0 & one_token==1
local pay = r(mean)/100
local Ppay_m_1 = string(`pay', "%5.2f")
noi: summ earnings if Task == "1. Raven Piece Rate" & bbin==1 & female==0 & eighty_tokens==1
local pay = r(mean)/100
local Ppay_m_80 = string(`pay', "%5.2f")
noi: summ earnings if Task == "1. Raven Piece Rate" & bbin==1 & female==1 & one_token==1
local pay = r(mean)/100
local Ppay_f_1 = string(`pay', "%5.2f")
noi: summ earnings if Task == "1. Raven Piece Rate" & bbin==1 & female==1 & eighty_tokens==1
local pay = r(mean)/100
local Ppay_f_80 = string(`pay', "%5.2f")

noi: summ earnings if Task == "2. Raven Tournament" & bbin==1 & female==0 & one_token==1
local pay = r(mean)/25
local Tpay_m_1 = string(`pay', "%5.2f")
noi: summ earnings if Task == "2. Raven Tournament" & bbin==1 & female==0 & eighty_tokens==1
local pay = r(mean)/25
local Tpay_m_80 = string(`pay', "%5.2f")
noi: summ earnings if Task == "2. Raven Tournament" & bbin==1 & female==1 & one_token==1
local pay = r(mean)/25
local Tpay_f_1 = string(`pay', "%5.2f")
noi: summ earnings if Task == "2. Raven Tournament" & bbin==1 & female==1 & eighty_tokens==1
local pay = r(mean)/25
local Tpay_f_80 = string(`pay', "%5.2f")
}

* expected payout in Tournament
generate Texpect = Tpay*Twin
generate Texcess = Texpect/Ppay
summ Ppay Tpay Twin Texpect Texcess if task_id==9 & bbin==1
bysort female: summ Ppay Tpay Twin Texpect Texcess if task_id==9 & bbin==1
bysort eighty_tokens female: summ Ppay Tpay Twin Texpect Texcess if task_id==9 & bbin==1

* save variables for each risk model
foreach v in Ppay Tpay Twin TwinT TwinP Texpect Texcess {
	generate `v'_`m' = `v'
}

* save data and drop to 1 bin
save tmp_gc, replace
keep if bbin == 1
tab sid if eighty_tokens==1
local n_80 = r(r)
tab sid if one_token==1
local n_1 = r(r)
di "There are `n_80' subjects in the 80-token treatment and `n_1' subjects in the 1-token treatment."

* comparison of risk preferences
bysort female: summ r_eut r_rdu eta phi
summ r_eut r_rdu eta phi

* welfare evaluation
generate welfare_select_`m' = .
generate welfare_submit_`m' = .

* welfare if chose to compete
generate welfare_selectT_`m' =.
generate welfare_submitT_`m' =.

qui {
if "`m'" == "eut" {
forvalues s=1/`Nsub' {

	summ r_eut if sid==`s'
	local r = r(mean)
	local rr = 1-`r'

	* EU for part 3
	local eu_piece = (`Ppay_`s''^`rr')/(`rr')
	local eu_t = (`Tpay_`s''^`rr')/(`rr') * `Twin_`s'' 

	local ce_piece = (`eu_piece'*`rr')^(1/`rr')
	local ce_t = (`eu_t'*`rr')^(1/`rr')

	local cs = abs(`ce_piece' - `ce_t')

	summ selectT if sid==`s'
	local selectT = r(mean)
	local cs_select = 0
	if `selectT' == 1 {
		local cs_select = `ce_t' - `ce_piece'
	}
	else {
		local cs_select = `ce_piece' - `ce_t'
	}
	replace welfare_select_eut = `cs_select' if sid==`s'
	replace welfare_selectT_eut = `ce_t' - `ce_piece' if sid==`s'

	* EU update for part 4
	local eu_t_ns = (`Tpay_`s''^`rr')/(`rr') * `Twin_`s'_ns' 
	local ce_t_ns = (`eu_t_ns'*`rr')^(1/`rr')
	local cs_ns = abs(`ce_piece' - `ce_t_ns')

	summ submitT if sid==`s'
	local submitT = r(mean)
	local cs_submit = 0
	if `submitT' == 1 {
		local cs_submit = `ce_t_ns' - `ce_piece'
	}
	else {
		local cs_submit = `ce_piece' - `ce_t_ns' 
	}
	replace welfare_submit_eut = `cs_submit' if sid==`s'
	replace welfare_submitT_eut = `ce_t_ns' - `ce_piece' if sid==`s'

	if `s' < 5 {
		noi: di "* subject `s' under EUT has ce_piece of `ce_piece' and ce_t of `ce_t', hence CS of `cs' from making the right choice in select task"
		noi: di "* subject `s' under EUT has ce_piece of `ce_piece' and ce_t of `ce_t_ns', hence CS of `cs_ns' from making the right choice in submit task"
		noi: di "*             under EUT the actual CS in select task is `cs_select' and actual CS in submit task is `cs_submit'"
		noi: di "                                  "
	}

}
}
}

noi {
if "`m'" == "rdu" {
forvalues s=1/`Nsub' {

	summ r_rdu if sid==`s'
	local r = r(mean)
	local rr = 1-`r'

	summ eta if sid==`s'
	local eta = r(mean)
	summ phi if sid==`s'
	local phi = r(mean)

	* EU for part 3
	local eu_piece = (`Ppay_`s''^`rr')/(`rr')
	if `Twin_`s'' > 0 & `Twin_`s'' < 1 {
		local dw_prob_win = exp((-`eta')*(-ln(`Twin_`s''))^`phi')
	}
	else {
		local dw_prob_win = `Twin_`s''
	}
	local eu_t = (`Tpay_`s''^`rr')/(`rr') * `dw_prob_win' 

	local ce_piece = (`eu_piece'*`rr')^(1/`rr')
	local ce_t = (`eu_t'*`rr')^(1/`rr')

	local cs = abs(`ce_piece' - `ce_t')

	summ selectT if sid==`s'
	local selectT = r(mean)
	local cs_select = 0
	if `selectT' == 1 {
		local cs_select = `ce_t' - `ce_piece'
	}
	else {
		local cs_select = `ce_piece' - `ce_t'
	}
	replace welfare_select_rdu = `cs_select' if sid==`s'
	replace welfare_selectT_rdu = `ce_t' - `ce_piece' if sid==`s'

	* EU update for part 4
	if `Twin_`s'_ns' > 0 & `Twin_`s'_ns' < 1 {
		local dw_prob_win = exp((-`eta')*(-ln(`Twin_`s'_ns'))^`phi')
	}
	else {
		local dw_prob_win = `Twin_`s'_ns'
	}
	local eu_t_ns = (`Tpay_`s''^`rr')/(`rr') * `dw_prob_win' 
	local ce_t_ns = (`eu_t_ns'*`rr')^(1/`rr')
	local cs_ns = abs(`ce_piece' - `ce_t_ns')

	summ submitT if sid==`s'
	local submitT = r(mean)
	local cs_submit = 0
	if `submitT' == 1 {
		local cs_submit = `ce_t_ns' - `ce_piece'
	}
	else {
		local cs_submit = `ce_piece' - `ce_t_ns' 
	}
	replace welfare_submit_rdu = `cs_submit' if sid==`s'
	replace welfare_submitT_rdu = `ce_t' - `ce_piece' if sid==`s'

	if `s' < 5 {
		noi: di "* subject `s' under RDU has ce_piece of `ce_piece' and ce_t of `ce_t', hence CS of `cs' from making the right choice in select task"
		noi: di "* subject `s' under RDU has Twin_s_ns `Twin_`s'_ns' and dw_prob_win `dw_prob_win' in the submit task"
		noi: di "* subject `s' under RDU has ce_piece of `ce_piece' and ce_t of `ce_t_ns', hence CS of `cs_ns' from making the right choice in submit task"
		noi: di "*             under RDU the actual CS in select task is `cs_select' and actual CS in submit task is `cs_submit'"
		noi: di "                                  "
	}

}
}
}

* drop variables re-generated
foreach v in Ppay Tpay Twin TwinT TwinP Texpect Texcess {
	drop `v'
}

* end of big loop over risk models
}
* end of qui
}

drop record
tab sid, missing
bysort sid: egen int record=seq()

summ welfare_* if record==1
bysort female: summ welfare_* if record==1
bysort female: summ welfare_* if record==1 & one_token==1
bysort female: summ welfare_* if record==1 & eighty_tokens==1

* collate for regression
save tmp, replace
keep if record==1
keep sid female one_token eighty_tokens selectT submitT welfare_select_eut welfare_submit_eut welfare_selectT_eut welfare_submitT_eut `bfi' `demog' Ppay_eut Tpay_eut TwinT_eut TwinP_eut
foreach v in welfare_select welfare_submit Ppay Tpay TwinT TwinP {
	rename `v'_eut `v'
}
generate int rdu = 0
tab eighty_tokens
save tmp_eut, replace

use tmp, clear
keep if record==1
keep sid female one_token eighty_tokens selectT submitT welfare_select_rdu welfare_submit_rdu  welfare_selectT_rdu welfare_submitT_rdu `bfi' `demog' Ppay_rdu Tpay_rdu TwinT_rdu TwinP_rdu
foreach v in welfare_select welfare_submit Ppay Tpay TwinT TwinP {
	rename `v'_rdu `v'
}
generate int rdu = 1
tab eighty_tokens
append using tmp_eut

* women, blacks and everyone that should have selected the T in part 3 and did -- should be 1 normatively
summ selectT if rdu==0 & female==1 & welfare_selectT_eut>0
summ selectT if rdu==0 & black==1 & welfare_selectT_eut>0
summ selectT if rdu==0 & welfare_selectT_eut>0

* women, blacks and everyone that should not have selected the T in part 3 and did not -- should be 0 normatively
summ selectT if rdu==0 & female==1 & welfare_selectT_eut<0
summ selectT if rdu==0 & black==1 & welfare_selectT_eut<0
summ selectT if rdu==0 & welfare_selectT_eut<0

* women, blacks and everyone that should have submitted the T in part 4 and did -- should be 1 normatively
summ submitT if rdu==0 & female==1 & welfare_submitT_eut>0
summ submitT if rdu==0 & black==1 & welfare_submitT_eut>0
summ submitT if rdu==0 & welfare_submitT_eut>0

* women, blacks and everyone that should not have submitted the T in part 4 and did not -- should be 0 normatively
summ submitT if rdu==0 & female==1 & welfare_submitT_eut<0
summ submitT if rdu==0 & black==1 & welfare_submitT_eut<0
summ submitT if rdu==0 & welfare_submitT_eut<0

* set up for next pictures
mylabels -2(1)4, prefix($) myscale(@) local(doll)
local doll `"-2 "-$2" -1 "-$1" 0 "$0" 1 "+$1" 2 "+$2" 3 "+$3" 4 "+$4""'
mylabels 0(10)40, suffix(%) myscale(@) local(pct)
local scolor "orange*0.75"
local nscolor "ltkhaki"

* fraction gaining from competition
generate int pos_eut = 0
replace pos_eut=1 if welfare_selectT_eut>0
tab pos_eut if rdu==0 

generate int pos_eut_ = 0
replace pos_eut_=1 if welfare_submitT_eut>0
tab pos_eut_ if rdu==0

generate int pos_rdu = 0
replace pos_rdu=1 if welfare_selectT_rdu>0
tab pos_rdu if rdu==1

generate int pos_rdu_ = 0
replace pos_rdu_=1 if welfare_submitT_rdu>0
tab pos_rdu_ if rdu==1

* pictures of ex ante decisions
histogram welfare_selectT_eut if rdu==0 & eighty_tokens==0 & welfare_selectT_eut<4.25, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Ante} Welfare Effect of Competing") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With Stress", ring(0) pos(1) size(medium)) saving(w1_s, replace)
histogram welfare_selectT_eut if rdu==0 & eighty_tokens==1 & welfare_selectT_eut<4.25, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Ante} Welfare Effect of Competing") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With Stress", ring(0) pos(1) size(medium)) saving(w80_s, replace)
histogram welfare_submitT_eut if rdu==0 & eighty_tokens==0 & welfare_submitT_eut<4.25, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Ante} Welfare Effect of Competing") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With No Stress", ring(0) pos(1) size(medium)) saving(w1_ns, replace)
histogram welfare_submitT_eut if rdu==0 & eighty_tokens==1 & welfare_submitT_eut<4.25, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Ante} Welfare Effect of Competing") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With No Stress", ring(0) pos(1) size(medium)) saving(w80_ns, replace)
gr combine w1_s.gph w1_ns.gph w80_s.gph w80_ns.gph, ycommon xcommon cols(2) imargin(small) title("{bf:A. Expected Utility Theory Risk Preferences}", size(large) span) saving(eut, replace)

histogram welfare_selectT_rdu if rdu==1 & eighty_tokens==0 & welfare_selectT_rdu<4.25, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Ante} Welfare Effect of Competing") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With Stress", ring(0) pos(1) size(medium)) saving(w1_s, replace)
histogram welfare_selectT_rdu if rdu==1 & eighty_tokens==1 & welfare_selectT_rdu<4.25, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Ante} Welfare Effect of Competing") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With Stress", ring(0) pos(1) size(medium)) saving(w80_s, replace)
histogram welfare_submitT_rdu if rdu==1 & eighty_tokens==0 & welfare_submitT_rdu<4.25, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Ante} Welfare Effect of Competing") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With No Stress", ring(0) pos(1) size(medium)) saving(w1_ns, replace)
histogram welfare_submitT_rdu if rdu==1 & eighty_tokens==1 & welfare_submitT_rdu<4.25, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Ante} Welfare Effect of Competing") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With No Stress", ring(0) pos(1) size(medium)) saving(w80_ns, replace)
gr combine w1_s.gph w1_ns.gph w80_s.gph w80_ns.gph, ycommon xcommon cols(2) imargin(small) title("{bf:B. Rank Dependent Utility Risk Preferences}", size(large) span) saving(rdu, replace)

if "$useRECOVERED" == "y" {
	gr combine eut.gph rdu.gph, rows(2) imargin(small) title("Figure 14: {it:Ex Ante} Welfare Effects" "of the Decision to Compete", size(vlarge) span) saving(figures/raven_14.gph, replace)
	gr export raven_14.png, replace
}

* pictures of actual decisions
mylabels -3(1)3, prefix($) myscale(@) local(doll)
local doll `"-3 "-$3" -2 "-$2" -1 "-$1" 0 "$0" 1 "+$1" 2 "+$2" 3 "+$3""'

histogram welfare_select if rdu==0 & eighty_tokens==0 & welfare_select<3 & welfare_select<3, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With Stress", ring(0) pos(1) size(medium)) saving(w1_s, replace)
histogram welfare_select if rdu==0 & eighty_tokens==1 & welfare_select<3 & welfare_select<3, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With Stress", ring(0) pos(1) size(medium)) saving(w80_s, replace)
histogram welfare_submit if rdu==0 & eighty_tokens==0 & welfare_submit<3 & welfare_submit>-3, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With No Stress", ring(0) pos(1) size(medium)) saving(w1_ns, replace)
histogram welfare_submit if rdu==0 & eighty_tokens==1 & welfare_submit<3 & welfare_submit>-3, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With No Stress", ring(0) pos(1) size(medium)) saving(w80_ns, replace)
gr combine w1_s.gph w1_ns.gph w80_s.gph w80_ns.gph, ycommon xcommon cols(2) imargin(small) title("{bf:A. Expected Utility Theory Risk Preferences}", size(large) span) saving(eut, replace)

histogram welfare_select if rdu==1 & eighty_tokens==0 & welfare_select<3 & welfare_select<3, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With Stress", ring(0) pos(1) size(medium)) saving(w1_s, replace)
histogram welfare_select if rdu==1 & eighty_tokens==1 & welfare_select<3 & welfare_select<3, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With Stress", ring(0) pos(1) size(medium)) saving(w80_s, replace)
histogram welfare_submit if rdu==1 & eighty_tokens==0 & welfare_submit<3 & welfare_submit>-3, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With No Stress", ring(0) pos(1) size(medium)) saving(w1_ns, replace)
histogram welfare_submit if rdu==1 & eighty_tokens==1 & welfare_submit<3 & welfare_submit>-3, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll', labsize(medsmall)) xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With No Stress", ring(0) pos(1) size(medium)) saving(w80_ns, replace)
gr combine w1_s.gph w1_ns.gph w80_s.gph w80_ns.gph, ycommon xcommon cols(2) imargin(small) title("{bf:B. Rank Dependent Utility Risk Preferences}", size(large) span) saving(rdu, replace)

if "$useRECOVERED" == "y" {
	gr combine eut.gph rdu.gph, rows(2) imargin(small) title("Figure 15: {it:Ex Post} Welfare Effects of the" "Observed Decision to Compete (or Not)", size(vlarge) span) saving(figures/raven_15.gph, replace)
	gr export raven_15.png, replace
}

* save and do by men and women
save tmp, replace
keep if female == 0

* pictures of actual decisions by 
histogram welfare_select if rdu==0 & eighty_tokens==0 & welfare_select<4.5, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With Stress", ring(0) pos(1) size(medium)) saving(w1_s, replace)
histogram welfare_select if rdu==0 & eighty_tokens==1 & welfare_select<4.5, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With Stress", ring(0) pos(1) size(medium)) saving(w80_s, replace)
histogram welfare_submit if rdu==0 & eighty_tokens==0 & welfare_select<4.5, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With No Stress", ring(0) pos(1) size(medium)) saving(w1_ns, replace)
histogram welfare_submit if rdu==0 & eighty_tokens==1 & welfare_select<4.5, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With No Stress", ring(0) pos(1) size(medium)) saving(w80_ns, replace)
gr combine w1_s.gph w1_ns.gph w80_s.gph w80_ns.gph, ycommon xcommon cols(2) imargin(small) title("{bf:A. Expected Utility Theory Risk Preferences}", size(large) span) saving(eut, replace)

histogram welfare_select if rdu==1 & eighty_tokens==0 & welfare_select<4.5, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With Stress", ring(0) pos(1) size(medium)) saving(w1_s, replace)
histogram welfare_select if rdu==1 & eighty_tokens==1 & welfare_select<4.5, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With Stress", ring(0) pos(1) size(medium)) saving(w80_s, replace)
histogram welfare_submit if rdu==1 & eighty_tokens==0 & welfare_select<4.5, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With No Stress", ring(0) pos(1) size(medium)) saving(w1_ns, replace)
histogram welfare_submit if rdu==1 & eighty_tokens==1 & welfare_select<4.5, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With No Stress", ring(0) pos(1) size(medium)) saving(w80_ns, replace)
gr combine w1_s.gph w1_ns.gph w80_s.gph w80_ns.gph, ycommon xcommon cols(2) imargin(small) title("{bf:B. Rank Dependent Utility Risk Preferences}", size(large) span) saving(rdu, replace)

gr combine eut.gph rdu.gph, rows(2) imargin(small) title("Men Only: {it:Ex Post} Welfare Effects of the" "Observed Decision to Compete (or Not)", size(vlarge) span) saving(figures/welfare_men, replace)
gr export welfare_men.png, replace

* restart
use tmp, clear
keep if female == 1

* pictures of actual decisions 
histogram welfare_select if rdu==0 & eighty_tokens==0 & welfare_select<4.5, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With Stress", ring(0) pos(1) size(medium)) saving(w1_s, replace)
histogram welfare_select if rdu==0 & eighty_tokens==1 & welfare_select<4.5, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With Stress", ring(0) pos(1) size(medium)) saving(w80_s, replace)
histogram welfare_submit if rdu==0 & eighty_tokens==0 & welfare_select<4.5, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With No Stress", ring(0) pos(1) size(medium)) saving(w1_ns, replace)
histogram welfare_submit if rdu==0 & eighty_tokens==1 & welfare_select<4.5, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With No Stress", ring(0) pos(1) size(medium)) saving(w80_ns, replace)
gr combine w1_s.gph w1_ns.gph w80_s.gph w80_ns.gph, ycommon xcommon cols(2) imargin(small) title("{bf:A. Expected Utility Theory Risk Preferences}", size(large) span) saving(eut, replace)

histogram welfare_select if rdu==1 & eighty_tokens==0 & welfare_select<4.5, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With Stress", ring(0) pos(1) size(medium)) saving(w1_s, replace)
histogram welfare_select if rdu==1 & eighty_tokens==1 & welfare_select<4.5, width(0.25) percent fcolor(`scolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With Stress", ring(0) pos(1) size(medium)) saving(w80_s, replace)
histogram welfare_submit if rdu==1 & eighty_tokens==0 & welfare_select<4.5, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("1 Token With No Stress", ring(0) pos(1) size(medium)) saving(w1_ns, replace)
histogram welfare_submit if rdu==1 & eighty_tokens==1 & welfare_select<4.5, width(0.25) percent fcolor(`nscolor') ytitle("") ylabel(`pct', labsize(small) angle(horizontal)) xtitle("{it:Ex Post} Welfare Effect of Observed Decision") xtitle(, margin(vsmall)) xlabel(`doll') xline(0, lwidth(medthick) lpattern(dash) lcolor(red)) title("80 Tokens With No Stress", ring(0) pos(1) size(medium)) saving(w80_ns, replace)
gr combine w1_s.gph w1_ns.gph w80_s.gph w80_ns.gph, ycommon xcommon cols(2) imargin(small) title("{bf:B. Rank Dependent Utility Risk Preferences}", size(large) span) saving(rdu, replace)

gr combine eut.gph rdu.gph, rows(2) imargin(small) title("Women Only: {it:Ex Post} Welfare Effects of the" "Observed Decision to Compete (or Not)", size(vlarge) span) saving(figures/welfare_women, replace)
gr export welfare_women.png, replace

* restart
use tmp, clear

* clean up
foreach x in eut rdu w1_s w1_ns w80_s w80_ns {
	erase `x'.gph
}

* reshape long
rename welfare_select welfare_0
rename welfare_submit welfare_1
reshape long welfare_, i(sid rdu) j(submit)
rename welfare_ welfare
tab eighty_tokens submit

* absolute welfare change
generate welfare_abs = abs(welfare)

* welfare under EUT

* regression
regress welfare female submit if one_token==1 & rdu==0
regress welfare female submit if eighty_tokens==1 & rdu==0

regress welfare female submit eighty_tokens if rdu==0
regress welfare i.female#i.submit i.female#i.eighty_tokens if rdu==0
margins, dydx(*)

summ welfare submit eighty_tokens `demog_i' `bfi'
regress welfare `demog_i' `bfi' i.female#i.submit i.female#i.eighty_tokens if rdu==0
test `bfi'
margins, dydx(*)

hetregress welfare i.female i.female#i.submit i.female#i.eighty_tokens, het(i.female i.eighty_tokens i.submit)
margins, dydx(*)

hetregress welfare i.female i.female#i.submit i.female#i.eighty_tokens if welfare<0, het(i.female i.eighty_tokens i.submit)
margins, dydx(*)

* easier to interpret
hetregress welfare_abs i.female i.female#i.submit i.female#i.eighty_tokens if welfare<0, het(i.female i.eighty_tokens i.submit)
margins, dydx(*)

* binary welfare
generate welfare_gain = 0
replace welfare_gain = 1 if welfare>0
label variable welfare_gain "Actual welfare gain (=1) or loss (=0)"

probit welfare_gain i.female i.female#i.submit i.female#i.eighty_tokens if rdu==0, vce(cluster sid)
margins, dydx(*)

probit welfare_gain `demog_i' i.female#i.submit i.female#i.eighty_tokens if rdu==0, vce(cluster sid)
margins, dydx(*)

probit welfare_gain `demog_i' `bfi' i.female#i.submit i.female#i.eighty_tokens if rdu==0, vce(cluster sid)
margins female black business noreligion

* binary covariates
generate optimistT = 0
replace optimistT = 1 if TwinT>0.25
label variable optimistT "Subjective probability of winning greater than 0.25 with tournament performance"

generate optimistP = 0
replace optimistP = 1 if TwinP>0.25
label variable optimistP "Subjective probability of winning greater than 0.25 with piece-rate performance"

summ Tpay, detail
local p25 = r(p25)
generate earnT = 0
replace earnT = 1 if Tpay>`p25' 
label variable earnT "Tournament earnings in top 25%"

summ Ppay, detail
local p25 = r(p25)
generate earnP = 0
replace earnP = 1 if Ppay>`p25' 
label variable earnT "Piece-Rate earnings in top 25%"


* log for appendix C
log using "Raven Gender and Competitiveness -- Results for Appendix C.log", replace name(c)

* tabulations
des welfare_gain `demog' `bfi' optimist* earn*, fullnames
summ welfare_gain optimist* earn*

* result 1: overall welfare gain RDU
summ welfare_gain if rdu==1

* comparison to EUT
summ welfare_gain if rdu==0

* result 2: welfare gain RDU with stress or no stress
summ welfare_gain if rdu==1 & submit==0
summ welfare_gain if rdu==1 & submit==1

* comparison to EUT
summ welfare_gain if rdu==0 & submit==0
summ welfare_gain if rdu==0 & submit==1

* result 3: unconditional welfare gain RDU for women 
tab welfare_gain female if rdu==1, col nofreq exact
tab welfare_gain female if rdu==1 & submit==0, col nofreq exact
tab welfare_gain female if rdu==1 & submit==1, col nofreq exact

* comparison to EUT
tab welfare_gain female if rdu==0, col nofreq exact
tab welfare_gain female if rdu==0 & submit==0, col nofreq exact
tab welfare_gain female if rdu==0 & submit==1, col nofreq exact

* conditioning on gender and interaction with 80 tokens
probit welfare_gain i.female i.female#i.eighty_tokens if rdu==1 & submit==0, vce(cluster sid)
margins, dydx(*)
probit welfare_gain i.female i.female#i.eighty_tokens if rdu==1 & submit==1, vce(cluster sid)
margins, dydx(*)

* conditioning on demographics
probit welfare_gain `demog_i' i.female#i.eighty_tokens if rdu==1 & submit==0, vce(cluster sid)
margins, dydx(*)
probit welfare_gain `demog_i' i.female#i.eighty_tokens if rdu==1 & submit==1, vce(cluster sid)
margins, dydx(*)

* conditioning on demographics and BFI
probit welfare_gain `demog_i' `bfi' i.female#i.eighty_tokens if rdu==1 & submit==0, vce(cluster sid)
margins, dydx(*)
probit welfare_gain `demog_i' `bfi' i.female#i.eighty_tokens if rdu==1 & submit==1, vce(cluster sid)
margins, dydx(*)

* result 4: conditioning on demographics, BFI and optimism and earnings
probit welfare_gain `demog_i' `bfi' i.optimistT i.earnT i.optimistT#i.earnT i.female#i.eighty_tokens if rdu==1, vce(cluster sid)
margins, dydx(*)

* comparison to EUT
probit welfare_gain `demog_i' `bfi' i.optimistT i.earnT i.optimistT#i.earnT i.female#i.eighty_tokens if rdu==0, vce(cluster sid)
margins, dydx(*)

probit welfare_gain `demog_i' `bfi' i.optimistT i.earnT i.optimistT#i.earnT i.female#i.eighty_tokens if rdu==1 & submit==0, vce(cluster sid)
margins, dydx(*)

* result(s) 5: no-stress in part 4, and conditioning on demographics, BFI and optimism and earnings
probit welfare_gain `demog_i' `bfi' i.optimistP i.earnP i.earnP i.optimistP#i.earnP i.female#i.eighty_tokens if rdu==1 & submit==1, vce(cluster sid)
margins, dydx(*)

* comparison to EUT
probit welfare_gain `demog_i' `bfi' i.optimistP i.earnP i.earnP i.optimistP#i.earnP i.female#i.eighty_tokens if rdu==0 & submit==1, vce(cluster sid)
margins, dydx(*)

* conditioning only on gender, and optimism and earnings
probit welfare_gain i.female i.optimistT i.earnT i.optimistT#i.earnT i.female#i.eighty_tokens if rdu==1, vce(cluster sid)
margins, dydx(*)
probit welfare_gain i.female i.optimistT i.earnT i.optimistT#i.earnT i.female#i.eighty_tokens if rdu==1 & submit==0, vce(cluster sid)
margins, dydx(*)
probit welfare_gain i.female i.optimistP i.earnP i.optimistP#i.earnP i.female#i.eighty_tokens if rdu==1 & submit==1, vce(cluster sid)
margins, dydx(*)

log close c
 
* pictures
use tmp, clear
erase tmp.dta

bysort sid: egen int record=seq()

local k "gaussian"
local k "epan"

mylabels -2(1)4, prefix($) myscale(@) local(doll)
local doll `"-3 "-$3" -2 "-$2" -1 "-$1" 0 "$0" 1 "$1" 2 "$2" 3 "$3" 4 "$4" "'
twoway (kdensity welfare_select if rdu==0 & record==1 & female==0, kernel(`k') lcolor(blue) lpattern(solid) lwidth(thick)) (kdensity welfare_select if rdu==0 & record==1 & female==1, kernel(`k') lcolor(pink) lwidth(thick)) if one_token==1, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Expected Welfare Gain or Loss) xtitle(, size(medium) margin(small)) xlabel(`doll') xline(0, lwidth(medthin) lpattern(dash) lcolor(black)) title("One Token: Compete with Stress", size(large) span margin(small)) legend(order(1 "Male" 2 "Female") rows(1) position(6) ring(1)) saving(stress1, replace)
twoway (kdensity welfare_submit if rdu==0 & record==1 & female==0, kernel(`k') lcolor(blue) lpattern(solid) lwidth(thick)) (kdensity welfare_submit if rdu==0 & record==1 & female==1, kernel(`k') lcolor(pink) lwidth(thick)) if one_token==1, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Expected Welfare Gain or Loss) xtitle(, size(medium) margin(small)) xlabel(`doll') xline(0, lwidth(medthin) lpattern(dash) lcolor(black)) title("One Token: Compete with No Stress", size(large) span margin(small)) legend(order(1 "Male" 2 "Female") rows(1) position(6) ring(1)) saving(nostress1, replace)
twoway (kdensity welfare_select if rdu==0 & record==1 & female==0, kernel(`k') lcolor(blue) lpattern(solid) lwidth(thick)) (kdensity welfare_select if rdu==0 & record==1 & female==1, kernel(`k') lcolor(pink) lwidth(thick)) if one_token==0, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Expected Welfare Gain or Loss) xtitle(, size(medium) margin(small)) xlabel(`doll') xline(0, lwidth(medthin) lpattern(dash) lcolor(black)) title("Eighty Tokens: Compete with Stress", size(large) span margin(small)) legend(order(1 "Male" 2 "Female") rows(1) position(6) ring(1)) saving(stress80, replace)
twoway (kdensity welfare_submit if rdu==0 & record==1 & female==0, kernel(`k') lcolor(blue) lpattern(solid) lwidth(thick)) (kdensity welfare_submit if rdu==0 & record==1 & female==1, kernel(`k') lcolor(pink) lwidth(thick)) if one_token==0, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Expected Welfare Gain or Loss) xtitle(, size(medium) margin(small)) xlabel(`doll') xline(0, lwidth(medthin) lpattern(dash) lcolor(black)) title("Eighty Tokens: Compete with No Stress", size(large) span margin(small)) legend(order(1 "Male" 2 "Female") rows(1) position(6) ring(1)) saving(nostress80, replace)
grc1leg2 stress1.gph nostress1.gph stress80.gph nostress80.gph, ycommon xcommon cols(2) imargin(small) title("Welfare Effects of the Decisions to Compete Under EUT", size(vlarge) span margin(medium)) saving(welfare_eut, replace)
gr export welfare_eut.png, replace

local doll `" -2 "-$2" -1 "-$1" 0 "$0" 1 "$1" 2 "$2" 3 "$3" 4 "$4" "'
twoway (kdensity welfare_select if rdu==1 & record==1 & female==0, kernel(`k') lcolor(blue) lpattern(solid) lwidth(thick)) (kdensity welfare_select if rdu==1 & record==1 & female==1, kernel(`k') lcolor(pink) lwidth(thick)) if one_token==1, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Expected Welfare Gain or Loss) xtitle(, size(medium) margin(small)) xlabel(`doll') xline(0, lwidth(medthin) lpattern(dash) lcolor(black)) title("One Token: Compete with Stress", size(large) span margin(small)) legend(order(1 "Male" 2 "Female") rows(1) position(6) ring(1)) saving(stress1, replace)
twoway (kdensity welfare_submit if rdu==1 & record==1 & female==0, kernel(`k') lcolor(blue) lpattern(solid) lwidth(thick)) (kdensity welfare_submit if rdu==1 & record==1 & female==1, kernel(`k') lcolor(pink) lwidth(thick)) if one_token==1, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Expected Welfare Gain or Loss) xtitle(, size(medium) margin(small)) xlabel(`doll') xline(0, lwidth(medthin) lpattern(dash) lcolor(black)) title("One Token: Compete with No Stress", size(large) span margin(small)) legend(order(1 "Male" 2 "Female") rows(1) position(6) ring(1)) saving(nostress1, replace)
twoway (kdensity welfare_select if rdu==1 & record==1 & female==0, kernel(`k') lcolor(blue) lpattern(solid) lwidth(thick)) (kdensity welfare_select if rdu==1 & record==1 & female==1, kernel(`k') lcolor(pink) lwidth(thick)) if one_token==0, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Expected Welfare Gain or Loss) xtitle(, size(medium) margin(small)) xlabel(`doll') xline(0, lwidth(medthin) lpattern(dash) lcolor(black)) title("Eighty Tokens: Compete with Stress", size(large) span margin(small)) legend(order(1 "Male" 2 "Female") rows(1) position(6) ring(1)) saving(stress80, replace)
twoway (kdensity welfare_submit if rdu==1 & record==1 & female==0, kernel(`k') lcolor(blue) lpattern(solid) lwidth(thick)) (kdensity welfare_submit if rdu==1 & record==1 & female==1, kernel(`k') lcolor(pink) lwidth(thick)) if one_token==0, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Expected Welfare Gain or Loss) xtitle(, size(medium) margin(small)) xlabel(`doll') xline(0, lwidth(medthin) lpattern(dash) lcolor(black)) title("Eighty Tokens: Compete with No Stress", size(large) span margin(small)) legend(order(1 "Male" 2 "Female") rows(1) position(6) ring(1)) saving(nostress80, replace)
grc1leg2 stress1.gph nostress1.gph stress80.gph nostress80.gph, ycommon xcommon cols(2) imargin(small) title("Welfare Effects of the Decisions to Compete Under RDU", size(vlarge) span margin(medium)) saving(welfare_rdu, replace)
gr export welfare_rdu.png, replace

* now need back the full data
use tmp_gc4, clear

* get the subjective probability of top rank in the tournament
generate Twin_rdu = .
forvalues s=1/`Nsub' {
	summ probs_rdu if Task == "6. Tournament Rank?" & bbin==1 & sid==`s'
	local Twin_`s' = r(mean)
	replace Twin_rdu = `Twin_`s'' if sid==`s'
}

* reports of probabilities: RDU recovered
twoway (kdensity Twin_rdu if task_id==9 & bbin==1 & female==0, kernel(gaussian) lcolor(blue) lwidth(thick)) (kdensity Twin_rdu if task_id==9 & bbin==1 & female==1, kernel(gaussian) lcolor(pink) lwidth(thick)) if one_token==1, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Subjective Probability) xtitle(, size(medsmall) margin(medium)) xline(0.25, lwidth(medthin) lpattern(dash) lcolor(black)) xlabel(0(.25)1) title(One Token) legend(order(1 "Males" 2 "Females") rows(1) position(6) ring(1)) saving(one, replace)
twoway (kdensity Twin_rdu if task_id==9 & bbin==1 & female==0, kernel(gaussian) lcolor(blue) lwidth(thick)) (kdensity Twin_rdu if task_id==9 & bbin==1 & female==1, kernel(gaussian) lcolor(pink) lwidth(thick)) if eighty_tokens==1, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Subjective Probability) xtitle(, size(medsmall) margin(medium)) xline(0.25, lwidth(medthin) lpattern(dash) lcolor(black)) xlabel(0(.25)1) title(Eighty Tokens) legend(order(1 "Males" 2 "Females") rows(1) position(6) ring(1)) saving(eighty, replace)
grc1leg2 one.gph eighty.gph, cols(2) title("Recovered Subjective Probability" "of Winning the Tournament", size(vlarge) span) subtitle("Kernel densities of individual beliefs") saving(reported_probs, replace)
gr export reported_probs.png, replace

local k "gaussian"
twoway (kdensity Twin_rdu if task_id==9 & bbin==1 & selectT==0, kernel(`k') lcolor(sand) lpattern(dash) lwidth(thick)) (kdensity Twin_rdu if task_id==9 & bbin==1 & selectT==1, kernel(`k') lcolor(black) lwidth(thick)) if one_token==1, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Subjective Probability) xtitle(, size(medium) margin(small)) xline(0.25, lwidth(medthin) lpattern(dash) lcolor(black)) xlabel(0(0.1)0.6) title("Compete with Stress", size(large) span margin(small)) legend(order(1 "Chose Piece Rate" 2 "Chose Tournament") rows(1) position(6) ring(1)) saving(stress, replace)
twoway (kdensity Twin_rdu if task_id==9 & bbin==1 & submitT==0, kernel(`k') lcolor(sand) lpattern(dash) lwidth(thick)) (kdensity Twin_rdu if task_id==9 & bbin==1 & submitT==1, kernel(`k') lcolor(black) lwidth(thick)) if one_token==1, ytitle("") ylabel(none, labsize(medsmall) angle(horizontal)) xtitle(Subjective Probability) xtitle(, size(medium) margin(small)) xline(0.25, lwidth(medthin) lpattern(dash) lcolor(black)) xlabel(0(0.1)0.6) title("Compete with No Stress", size(large) span margin(small)) legend(order(1 "Chose Piece Rate" 2 "Chose Tournament") rows(1) position(6) ring(1)) saving(nostress, replace)
grc1leg2 stress.gph nostress.gph, ycommon xcommon cols(2) imargin(small) title("The Decision to Compete Under Stress or" "With No Stress, and the Recovered" "Subjective Probability of Winning the Tournament", size(vlarge) span margin(medium)) saving(stressed, replace)
gr export stressed.png, replace
erase stress.gph
erase nostress.gph

* pictures of RDU beliefs
save tmp, replace
keep if (Task == "5. Piece Rate Rank?" | Task == "6. Tournament Rank?") & bbin<=4
generate probs_m = probs_rdu if female==0
generate probs_f = probs_rdu if female==1
drop if sid == .
sort sid bbin

* with no numbers, for text
graph bar (mean) probs_m (mean) probs_f if one_token==1 & Task == "5. Piece Rate Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(blue) lcolor(blue)) bar(2, fcolor(pink) lcolor(pink)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Men" 2 "Women") region(col(white)) rows(2) size(small) position(1) ring(0)) title("Piece Rate Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thick)) saving(piece, replace)
graph bar (mean) probs_m (mean) probs_f if one_token==1 & Task == "6. Tournament Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(blue) lcolor(blue)) bar(2, fcolor(pink) lcolor(pink)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Men" 2 "Women") region(col(white)) rows(2) size(small) position(1) ring(0)) title("Tournament Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thick)) saving(tournament, replace)
gr combine piece.gph tournament.gph, cols(2) title("{bf:A. One Token}", size(medlarge) span) saving(one, replace)

graph bar (mean) probs_m (mean) probs_f if one_token==0 & Task == "5. Piece Rate Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(blue) lcolor(blue)) bar(2, fcolor(pink) lcolor(pink)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Men" 2 "Women") region(col(white)) rows(2) size(small) position(1) ring(0)) title("Piece Rate Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thick)) saving(piece, replace)
graph bar (mean) probs_m (mean) probs_f if one_token==0 & Task == "6. Tournament Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(blue) lcolor(blue)) bar(2, fcolor(pink) lcolor(pink)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Men" 2 "Women") region(col(white)) rows(2) size(small) position(1) ring(0)) title("Tournament Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thick)) saving(tournament, replace)
gr combine piece.gph tournament.gph, cols(2) title("{bf:B. Eighty Tokens}", size(medlarge) span) saving(eighty, replace)

if "$useRECOVERED" == "y" {
	gr combine one.gph eighty.gph, imargin(vsmall) rows(2) title("Figure 16: `belief_text' on the Probability of" "Personal Performance Ranks by Men and Women", size(vlarge) span) saving(figures/raven_16.gph, replace)
	gr export raven_16.png, replace
}
else {
	gr combine one.gph eighty.gph, imargin(vsmall) rows(2) title("Figure B16: `belief_text' on the Probability of" "Personal Performance Ranks by Men and Women", size(vlarge) span) saving(figures/raven_B16.gph, replace)
	gr export raven_B16.png, replace
}

* with numbers, for appendix
graph bar (mean) probs_m (mean) probs_f if one_token==1 & Task == "5. Piece Rate Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(blue) lcolor(blue)) bar(2, fcolor(pink) lcolor(pink)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Men" 2 "Women") rows(2) size(small) position(1) ring(0)) title("Piece Rate Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thin)) blabel(bar, format(%3.2f)) saving(piece, replace)
graph bar (mean) probs_m (mean) probs_f if one_token==1 & Task == "6. Tournament Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(blue) lcolor(blue)) bar(2, fcolor(pink) lcolor(pink)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Men" 2 "Women") rows(2) size(small) position(1) ring(0)) title("Tournament Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thin)) blabel(bar, format(%3.2f)) saving(tournament, replace)
gr combine piece.gph tournament.gph, cols(2) title("{bf:A. One Token}", size(medlarge) span) saving(one, replace)

graph bar (mean) probs_m (mean) probs_f if one_token==0 & Task == "5. Piece Rate Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(blue) lcolor(blue)) bar(2, fcolor(pink) lcolor(pink)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Men" 2 "Women") rows(2) size(small) position(1) ring(0)) title("Piece Rate Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thin)) blabel(bar, format(%3.2f)) saving(piece, replace)
graph bar (mean) probs_m (mean) probs_f if one_token==0 & Task == "6. Tournament Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(blue) lcolor(blue)) bar(2, fcolor(pink) lcolor(pink)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Men" 2 "Women") rows(2) size(small) position(1) ring(0)) title("Tournament Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thin)) blabel(bar, format(%3.2f)) saving(tournament, replace)
gr combine piece.gph tournament.gph, cols(2) title("{bf:B. Eighty Tokens}", size(medlarge) span) saving(eighty, replace)

if "$useRECOVERED" == "y" {
	gr combine one.gph eighty.gph, imargin(vsmall) rows(2) title("Figure C1: `belief_text' on the Probability of" "Personal Performance Ranks by Men and Women", size(vlarge) span) saving(figures/raven_C1.gph, replace)
	gr export raven_C1.png, replace
}

* black and non-black
replace probs_m = probs if black==0
replace probs_f = probs if black==1
sort sid bbin
list sid bbin probs* black if Task == "5. Piece Rate Rank?", noobs sepby(sid)

graph bar (mean) probs_m (mean) probs_f if one_token==1 & Task == "5. Piece Rate Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(stone) lcolor(stone)) bar(2, fcolor(black) lcolor(black)) bargap(0) outergap(0) ylabel(0(0.05)0.35, labsize(medium) angle(horizontal)) legend(order(1 "Non-Blacks" 2 "Blacks") rows(1) size(medsmall) position(6) ring(1)) title("Piece Rate Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thick)) saving(piece, replace)
graph bar (mean) probs_m (mean) probs_f if one_token==1 & Task == "6. Tournament Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(stone) lcolor(stone)) bar(2, fcolor(black) lcolor(black)) bargap(0) outergap(0) ylabel(0(0.05)0.35, labsize(medium) angle(horizontal)) legend(order(1 "Non-Blacks" 2 "Blacks") rows(1) size(medsmall) position(6) ring(1)) title("Tournament Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thick)) saving(tournament, replace)
grc1leg2 piece.gph tournament.gph, cols(2) title("Reported Beliefs on Probability of Rank with One Token", size(vlarge) span) saving(reported_ranks1, replace)
gr export reported_ranks1.png, replace

graph bar (mean) probs_m (mean) probs_f if one_token==1 & Task == "5. Piece Rate Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(stone) lcolor(stone)) bar(2, fcolor(black) lcolor(black)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Non-Blacks" 2 "Blacks") rows(1) size(small) position(1) ring(0)) title("Piece Rate Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thin)) blabel(bar, format(%3.2f)) saving(piece, replace)
graph bar (mean) probs_m (mean) probs_f if one_token==1 & Task == "6. Tournament Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(stone) lcolor(stone)) bar(2, fcolor(black) lcolor(black)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Non-Blacks" 2 "Blacks") rows(1) size(small) position(1) ring(0)) title("Tournament Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thin)) blabel(bar, format(%3.2f)) saving(tournament, replace)
gr combine piece.gph tournament.gph, cols(2) title("{bf:A. One Token}", size(medlarge) span) saving(one, replace)

graph bar (mean) probs_m (mean) probs_f if one_token==0 & Task == "5. Piece Rate Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(stone) lcolor(stone)) bar(2, fcolor(black) lcolor(black)) bargap(0) outergap(0) ylabel(0(0.05)0.35, labsize(medium) angle(horizontal)) legend(order(1 "Non-Blacks" 2 "Blacks") rows(1) size(medsmall) position(6) ring(1)) title("Piece Rate Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thick)) saving(piece, replace)
graph bar (mean) probs_m (mean) probs_f if one_token==0 & Task == "6. Tournament Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(stone) lcolor(stone)) bar(2, fcolor(black) lcolor(black)) bargap(0) outergap(0) ylabel(0(0.05)0.35, labsize(medium) angle(horizontal)) legend(order(1 "Non-Blacks" 2 "Blacks") rows(1) size(medsmall) position(6) ring(1)) title("Tournament Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thick)) saving(tournament, replace)
grc1leg2 piece.gph tournament.gph, cols(2) title("Reported Beliefs on Probability of Rank with Eighty Tokens", size(vlarge) span) saving(reported_ranks80, replace)
gr export reported_ranks80.png, replace

graph bar (mean) probs_m (mean) probs_f if one_token==0 & Task == "5. Piece Rate Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(stone) lcolor(stone)) bar(2, fcolor(black) lcolor(black)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Non-Blacks" 2 "Blacks") rows(1) size(small) position(1) ring(0)) title("Piece Rate Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thin)) blabel(bar, format(%3.2f)) saving(piece, replace)
graph bar (mean) probs_m (mean) probs_f if one_token==0 & Task == "6. Tournament Rank?", over(bbin, gap(*0.3) label(labsize(medsmall))) bar(1, fcolor(stone) lcolor(stone)) bar(2, fcolor(black) lcolor(black)) bargap(0) outergap(0) ylabel(0(0.1)0.4, labsize(medium) angle(horizontal)) legend(order(1 "Non-Blacks" 2 "Blacks") rows(1) size(small) position(1) ring(0)) title("Tournament Rank", size(large)) yline(0.25, lpattern(dash) lcolor(black) lwidth(thin)) blabel(bar, format(%3.2f)) saving(tournament, replace)
gr combine piece.gph tournament.gph, cols(2) title("{bf:B. Eighty Tokens}", size(medlarge) span) saving(eighty, replace)

if "$useRECOVERED" == "y" {
	gr combine one.gph eighty.gph, imargin(vsmall) rows(2) title("Figure C2: `belief_text' on the Probability of" "Personal Performance Ranks by Blacks and Non-Blacks", size(vlarge) span) saving(figures/raven_C2.gph, replace)
	gr export raven_C2.png, replace
}

* collate actual tournament payouts
use tmp, clear
keep if Task == "2. Raven Tournament"
keep if bbin==1
keep sid one_token eighty_tokens period female earnings
collapse (sum) earnings (mean) female one_token eighty_tokens, by(sid)
summ
list, noobs

* calculate probability of each player winning Tournament
summ sid
local Nsub_ = r(max)
save tmp, replace

set seed 1234
qui {
forvalues s=1/`Nsub_' {

	* get the data
	use tmp, clear

	* get the earnings being evaluated
	summ earnings if sid==`s'
	local mypay = r(mean)
	local win`s' = 0
	
	* randomize order
	local Nrandom = 100
	forvalues x=1/`Nrandom' {
		use tmp, clear
		drop if sid == `s'
		sample 3
		list sid earnings
		summ earnings
		local best = r(max)
		if `mypay' > `best' {
			local win`s' = `win`s''+1
		}
	}
	local winprob`s' = `win`s''/`Nrandom'
	di "    * subject `s' earnings were `mypay', and has won `win`s'' times out of `Nrandom', with probability `winprob`s''"

}
}

* collate
use tmp, clear
generate win_prob = .
generate prob_belief = .
forvalues s=1/`Nsub_' {
	replace win_prob = `winprob`s'' if sid==`s'
	replace prob_belief = `Twin_`s'' if sid==`s'
}
bysort female: summ win_prob if one_token==1
bysort female: summ win_prob if eighty_tokens==1
erase tmp.dta

* picture of belief and empirical probability
sort prob_belief
list prob_belief win_prob, noobs
pwcorr prob_belief win_prob
twoway (kdensity win_prob if female==0, kernel(gaussian) lcolor(blue) lwidth(medthick)) (kdensity win_prob if female==1, kernel(gaussian) lcolor(pink) lwidth(medthick)), yscale(off) xtitle(Empirical Probability of Winning the Tournament) xtitle(, size(medium) margin(medium)) xline(0.25, lwidth(medthin) lpattern(dash) lcolor(black)) xlabel(0(.25)1) title(Empirical Chance of Winning the Tournament, size(vlarge)) subtitle(Calculated by simulating realized Tournament earnings, size(medsmall) margin(medsmall)) legend(order(1 "Male" 2 "Female") rows(2) position(3) ring(0)) saving(winprobs1, replace)
gr export winprobs1.png, replace
twoway (kdensity win_prob if female==0 & one_token==1, kernel(gaussian) lcolor(blue) lwidth(medthick)) (kdensity win_prob if female==1 & one_token==1, kernel(gaussian) lcolor(pink) lwidth(medthick)), yscale(off) xtitle(Empirical Probability of Winning the Tournament) xtitle(, size(medium) margin(medium)) xline(0.25, lwidth(medthin) lpattern(dash) lcolor(black)) xlabel(0(.25)1) title(One Token) legend(order(1 "Male" 2 "Female") rows(1) position(6) ring(1)) saving(one, replace)
twoway (kdensity win_prob if female==0 & one_token==0, kernel(gaussian) lcolor(blue) lwidth(medthick)) (kdensity win_prob if female==1 & one_token==0, kernel(gaussian) lcolor(pink) lwidth(medthick)), yscale(off) xtitle(Empirical Probability of Winning the Tournament) xtitle(, size(medium) margin(medium)) xline(0.25, lwidth(medthin) lpattern(dash) lcolor(black)) xlabel(0(.25)1) title(Eighty Tokens) legend(order(1 "Male" 2 "Female") rows(1) position(6) ring(1)) saving(eighty, replace)
grc1leg2 one.gph eighty.gph, cols(2) title(Empirical Chance of Winning the Tournament, size(vlarge)) subtitle(Calculated by simulating realized Tournament earnings, size(medsmall) margin(medsmall)) saving(winprobs2, replace)
gr export winprobs2.png, replace

twoway (scatter prob_belief win_prob if female==0, sort mcolor(blue) msymbol(circle)) (scatter prob_belief win_prob if female==1, sort mcolor(pink) msymbol(circle)) (line prob_belief prob_belief, sort lcolor(black) lpattern(dash)), ytitle("Empirical" "Probability" "of Winning") ytitle(, size(medium) orientation(horizontal) margin(medium)) ylabel(0(0.25)1, angle(horizontal)) xtitle("Subjective Probability of Winning") xtitle(, size(medium) margin(medium)) xlabel(0(.25)1) title("Empirical {it:Versus} Subjective Probability" "of Winning the Tournament", size(vlarge) margin(medium)) legend(order(1 "Male" 2 "Female") rows(1)) saving(winprobs3, replace)
gr export winprobs3.png, replace
twoway (scatter prob_belief win_prob if female==0 & one_token==1, sort mcolor(blue) msymbol(circle)) (scatter prob_belief win_prob if female==1 & one_token==1, sort mcolor(pink) msymbol(circle)) (line prob_belief prob_belief, sort lcolor(black) lpattern(dash)), ytitle("Empirical" "Probability" "of Winning") ytitle(, size(medium) orientation(horizontal) margin(medium)) ylabel(0(0.25)1, angle(horizontal)) xtitle("Subjective Probability of Winning") xtitle(, size(medium) margin(medium)) xlabel(0(.25)1) title(One Token) legend(order(1 "Male" 2 "Female") rows(1)) saving(one, replace)
twoway (scatter prob_belief win_prob if female==0 & one_token==0, sort mcolor(blue) msymbol(circle)) (scatter prob_belief win_prob if female==1 & one_token==0, sort mcolor(pink) msymbol(circle)) (line prob_belief prob_belief, sort lcolor(black) lpattern(dash)), ytitle("Empirical" "Probability" "of Winning") ytitle(, size(medium) orientation(horizontal) margin(medium)) ylabel(0(0.25)1, angle(horizontal)) xtitle("Subjective Probability of Winning") xtitle(, size(medium) margin(medium)) xlabel(0(.25)1) title(Eighty Tokens) legend(order(1 "Male" 2 "Female") rows(1)) saving(eighty, replace)
grc1leg2 one.gph eighty.gph, cols(2) title("Empirical {it:Versus} Subjective Probability" "of Winning the Tournament", size(vlarge) margin(small)) saving(winprobs4, replace)
gr export winprobs4.png, replace

* Table 2 payouts and probabilities
di "For the 80 token case, the reported probability of winning the Tournament under Stress for men was `Twin_m_80', and was `Twin_f_80' for women. "
di "For the 80 token case, the reported probability of winning the Tournament with no Stress for men was `Twin_m_80_ns', and was `Twin_f_80_ns' for women. "
di "For the 80 token case, the Piece Rate payout for men was $`Ppay_m_80', and was $`Ppay_f_80' for women. "
di "For the 80 token case, the Tournament payout for men, conditional on winning, was $`Tpay_m_80', and was $`Tpay_f_80' for women. "

di "For the 1 token case, the reported probability of winning the Tournament under Stress for men was `Twin_m_1', and was `Twin_f_1' for women. "
di "For the 1 token case, the reported probability of winning the Tournament with no Stress for men was `Twin_m_1_ns', and was `Twin_f_1_ns' for women. "
di "For the 1 token case, the Piece Rate payout for men was $`Ppay_m_1', and was $`Ppay_f_1' for women. "
di "For the 1 token case, the Tournament payout for men, conditional on winning, was $`Tpay_m_1', and was $`Tpay_f_1' for women. "

* PDF document
* start a PDF
	putpdf begin, font("Candara",12) margin(left,1) margin(right,1)

	putpdf paragraph, font("",14) halign(center)
	putpdf text ("Tournament Behavior and Raven Matrices"), bold linebreak(2)

	local d = c(current_date)
	local t = c(current_time)
	putpdf paragraph, font("",12) halign(center)
	putpdf text ("`d'   `t'"), linebreak(2)

	putpdf paragraph, font("",12) halign(left)

	putpdf text ("        To date there have been `Nsub' subjects, each reporting their beliefs on the 8 alternatives for each of 36 of the Raven Progressive Matrices test of ")
	putpdf text ("fluid intelligence. The belief interface employs a Quadratic Scoring Rule (QSR) ")
	putpdf text ("with parameters chosen to allow a perfect allocation of 80 tokens to the correct interval to be rewarded with $2. ")
	putpdf text ("Subjects must allocate all 80 tokens for 36 different tasks, with each task paid. In the Gender & Competitiveness experiments all Raven questions are scrambled. ")
	putpdf text (" "), linebreak(2)

	putpdf text ("        Samples for the treatments in the 2022 sessions are as follows: ")
	putpdf text ("Scrambled with 80 Tokens"), bold
	putpdf text (" = `n_80', ")
	putpdf text ("Scrambled with 1 Token"), bold
	putpdf text (" = `n_1'.")
	putpdf text (" "), linebreak(2)

	putpdf text ("        Now some finger-math for each subject from the data, evaluating expected payoffs from chooseing Piece Rate and Tournament. ")
	putpdf text ("The payoffs are based on actual performance by the subject in Task #1 and Task #2, although they were not told their earnings until the end of session. ")
	putpdf text ("The subjective probability of having the top rank in the Tournament is reported by the subject in Task #6, and incentivized by a QSR. "), linebreak(1)
	forvalues s=1/`Nsub' {
		putpdf text ("   * Subject `s': $`Ppay_`s'_' in Piece Rate, $`Tpay_`s'_' in Tournament win, belief of `Twin_`s'_' of winning, so expecting $`Texpect_`s'_' from Tournament"), linebreak(1) font("",9)
	}
	* re-set font
	putpdf paragraph, font("",12)
	putpdf text ("So we see some striking effects of the subjective probability winning. Quite a few subjects place 0 probability on winning (e.g., subjects 32 and 73), ")
	putpdf text ("while some think very highly of themselves (e.g., subjects 4 and 10). There are some displays below of pooled beliefs of winning the tournament, broken down by gender. ")
	putpdf text ("And one subject, #61, lost for the last task #6, so has a missing subjective probability. For now these are reports, not recovered beliefs. ")
	putpdf text (" "), linebreak(2)

	putpdf text ("        For the pooled finger-math Excel calculation we need some data. ")
	putpdf text ("For the 1 token case, the reported probability of winning the Tournament under Stress for men was `Twin_m_1', and was `Twin_f_1' for women. ")
	putpdf text ("For the 80 token case, the reported probability of winning the Tournament under Stress for men was `Twin_m_80', and was `Twin_f_80' for women. ")
	putpdf text ("For the 1 token case, the reported probability of winning the Tournament with no Stress for men was `Twin_m_1_ns', and was `Twin_f_1_ns' for women. ")
	putpdf text ("For the 80 token case, the reported probability of winning the Tournament with no Stress for men was `Twin_m_80_ns', and was `Twin_f_80_ns' for women. ")
	putpdf text ("For the 1 token case, the Piece Rate payout for men was $`Ppay_m_1', and was $`Ppay_f_1' for women. ")
	putpdf text ("For the 80 token case, the Piece Rate payout for men was $`Ppay_m_80', and was $`Ppay_f_80' for women. ")
	putpdf text ("For the 1 token case, the Tournament payout for men, conditional on winning, was $`Tpay_m_1', and was $`Tpay_f_1' for women. ")
	putpdf text ("For the 80 token case, the Tournament payout for men, conditional on winning, was $`Tpay_m_80', and was $`Tpay_f_80' for women. ")

	local page = 3

	putpdf pagebreak
	putpdf paragraph, halign(right) font("Candara",10)
	local page = `page' + 1
	putpdf text ("Page `page'"), linebreak(1)
	putpdf paragraph, halign(center)
	putpdf image raven_14.png, linebreak width(6)
	putpdf image raven_15.png, linebreak width(6)

	putpdf pagebreak
	putpdf paragraph, halign(right) font("Candara",10)
	local page = `page' + 1
	putpdf text ("Page `page'"), linebreak(1)
	putpdf paragraph, halign(center)
	if "$useRECOVERED" == "y" {
		putpdf image raven_16.png, linebreak width(6)
	}
	else {
		putpdf image raven_B16.png, linebreak width(6)
	}
	putpdf image raven_D1.png, linebreak width(6)

	putpdf pagebreak
	putpdf paragraph, halign(right) font("Candara",10)
	local page = `page' + 1
	putpdf text ("Page `page'"), linebreak(1)
	putpdf paragraph, halign(center)
	putpdf image reported_probs.png, linebreak width(6)
	putpdf image stressed.png, linebreak width(6)

	putpdf pagebreak
	putpdf paragraph, halign(right) font("Candara",10)
	local page = `page' + 1
	putpdf text ("Page `page'"), linebreak(1)
	putpdf paragraph, halign(center)
	putpdf image winprobs1.png, linebreak width(6)
	putpdf image winprobs2.png, linebreak width(6)

	putpdf pagebreak
	putpdf paragraph, halign(right) font("Candara",10)
	local page = `page' + 1
	putpdf text ("Page `page'"), linebreak(1)
	putpdf paragraph, halign(center)
	putpdf image winprobs3.png, linebreak width(6)
	putpdf image winprobs4.png, linebreak width(6)

	putpdf pagebreak
	putpdf paragraph, halign(right) font("Candara",10)
	local page = `page' + 1
	putpdf text ("Page `page'"), linebreak(1)
	putpdf paragraph, halign(center)
	putpdf image welfare_eut.png, linebreak width(6)
	putpdf image welfare_rdu.png, linebreak width(6)
	
* save the PDF report
if "$useRECOVERED" == "y" {
	putpdf save "Tournament Behavior and Raven Matrices using Recovered Beliefs.pdf", replace
}
else {
	putpdf save "Tournament Behavior and Raven Matrices using Reported Beliefs.pdf", replace
}

* end of $doRaven
}

* clean up
capture: erase tmp_beliefs.dta
capture: erase tmp.dta
capture: erase tmp_eut.dta
capture: erase tmp_gc.dta
foreach x in raven_14 raven_15 raven_16 welfare_eut welfare_rdu stressed eighty one piece tournament reported_ranks1 reported_ranks1_extra reported_ranks80 reported_ranks80_extra reported_probs selectedT winprobs1 winprobs2 winprobs3 winprobs4 stress nostress stress1 nostress1 stress80 nostress80 {
	capture: erase `x'.png
	capture: erase `x'.gph
}

* time taken
timer off 1
timer list
local secs = r(t1)
local mins = `secs'/60
local hrs = `mins'/60
local secs_ = string(`secs', "%10.0f")
local mins_ = string(`mins', "%4.1f")
local hrs_ = string(`hrs', "%4.2f")
di "Calculations took `secs_' seconds, `mins_' minutes, or `hrs_' hours."

log close raven
